2

I can't make a list with realm in order to use it with a realm ListView.

I need to make 2 or 3 ListViews, you can see the pieces of code below:

realm.js:

const Realm = require ('realm');

class UserEntrySchema extends Realm.Object {}
UserEntrySchema.schema = {
   name:'User',
   primaryKey:'id',
   properties:{
     id:'int',
     name:'string',
     username: 'string',
     email: 'string',
   }
};

class UserListSchema extends Realm.Object {}
UserListSchema.schema = {
  name:'UserList',
  properties: {
    users :{type:'list', objectType:'User'}
  }
};

class HistorySchema extends Realm.Object {}
HistorySchema.schema = {
  name : 'History',
  properties :{
    items : {type:'list',objectType:'User'}
  }
};

export default new Realm({
  schema:[UserEntrySchema,UserListSchema,HistorySchema], schemaVersion:0});

I make a first ListView with the following code:

export default class SearchTabScreen1 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchText:'',
      data:[]
    };
}

  componentDidMount(){
    this.fetchUsers();
  }

  fetchUsers(){
    console.log("FEEEEEETCH");
    fetch('http://jsonplaceholder.typicode.com/users')
        .then((response) => response.json())
        .then((responseJson) =>  {
          this.setState({
            data : responseJson
          });
          var data = this.state.data;
          realm.write(() => {
            for (var i = 0; i < data.length; i++){
              let myUser = realm.create('User',data[i],true);
         }
         console.log("ALLUSER", realm.objects('User'));
       });
      })
        .catch(function(e) {    // Failure callback registartion
              alert('Failure fetching data');
              console.log(e)
    });
  }

I tried to make a list property using

UserListSchema

with no success.

And for now this ListView works fine even when I'm using

realm.objects('User')

as datasource.

I don't know if it's good to do it like that or not.

The second ListView is a "search history", when a row of the first ListView is clicked, it called the following method that pushes another screen (I am using react-native-navigation package) and populate a realm list. I would like to use this list as datasource for the 'history ListView".

onPushPress(rowData) {
    this.props.navigator.showModal({
      title: "Random Title",
      screen: "Project.WordDefinition",
      passProps: {
        definition: rowData.name
      }
    });
      realm.write(() => {
      let historyList = realm.create('History',{},true);
      historyList.items.push({rowData});
    });
  }
}

I got this error:

'Property' must be of type number

I also tried:

onPushPress(rowData) {
    console.log("ROWDATA", rowData);
    this.props.navigator.showModal({
      title: "Titre",
      screen: "AccessiDico.WordDefinition",
      passProps: {
        definition: rowData.name
      }
    });
      realm.write(() => {
      let historyList = realm.create('History',{},true);
      historyList.items.push({
        id:rowData.id,
        name:rowData.name,
        username: rowData.username,
        email: rowData.email,
      });

      console.log("ROWDATA",rowData);
      console.log("ITEMS",realm.objects('History'));
      console.log("List",historyList.items);
    });
  }
}

And I got this error:

Attempting to create an object of type 'User' with an existing primary key value

Does it means I can't use "my users" in the 'UserEntrySchema' to push them within a realm list ?

I would really appreciate some help, it has been a week that I am hard stuck with this :+1:

Thanks !

PS: Here how the history ListView is coded:

export default class HistoryTabScreen2 extends Component {
  constructor(props) {
    super(props);
    // if you want to listen on navigator events, set this up
    //this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
        postDataSource: ds.cloneWithRows(realm.objects('History')),
    };
  }

  renderRow(rowData, sectionId, rowId, highlightRow){
    return(
    <TouchableHighlight onPress={this.onPushPress.bind(this)}>
      <View style={styles.row}>
        <Text style={styles.rowText}>{rowData.name}</Text>
      </View>
    </TouchableHighlight>
    )
  }


  render(){
    return(
        <ListView
          dataSource={this.state.postDataSource}
          renderRow={this.renderRow.bind(this)}
        />
    );
  }

And the log of my rowData when I clicked a row of the ListView:

'ROWDATA', { id: 5,

   name: 'Chelsey Dietrich',

   username: 'Kamren',

   email: 'Lucio_Hettinger@annie.ca',

   address: 

    { street: 'Skiles Walks',

      suite: 'Suite 351',

      city: 'Roscoeview',

      zipcode: '33263',

      geo: { lat: '-31.8129', lng: '62.5342' } },

   phone: '(254)954-1289',

   website: 'demarco.info',

   company: 

    { name: 'Keebler LLC',

      catchPhrase: 'User-centric fault-tolerant solution',

      bs: 'revolutionize end-to-end systems' } }
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
K Soze
  • 163
  • 1
  • 13
  • Do you seriously expect anybody to read an essay? [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – Christoph May 03 '17 at 02:43

1 Answers1

2

I just responded to a question about list objects. take a look at this link, and then ask for further clarification if you need it. At the end of the post I provided a working example of creating/modifying/appending/deleting objects from a realm List object. How can I properly copy objects from one Realm object to another object

To create a list is pretty straightforward, here's the simplest case:

class Letters: Object {
    var letterList = List<Letter>()
}

So to create a list, you need to know the Object subclass you will be using. (Letter in the above example).

To add to the list, you create an object (item - below), and then append to the list:

firstList.letterList.append(item)
Community
  • 1
  • 1
Mozahler
  • 4,958
  • 6
  • 36
  • 56
  • Hi, ty for your answer. I choosed to not using list property as soon as I can display the DB content in my ListViews without it. I simply set my ListView's DataSource with `realm.objects('dbName')` and update it with `cloneWithRows(realm.objects('dbName')` – K Soze May 04 '17 at 10:58