Realm-js: [RN] Data storing in realm DB on every boot of the app

Created on 25 Apr 2017  路  3Comments  路  Source: realm/realm-js

Hi, (I don't know if it's the right place to ask this kind of question. Let me know if it's not)

I can't figure out how to fetch my data within my realm object properly:

I fetch a JSON file within the life cycle method componentDidMount() and I store it in my realm object (in the same method).
But everytime the app starts, it adds the JSON file's data again to the DB which is a normal.
So I want to know if there is a proper way to do it once or a better way.

And one more thing: I want to use this realm DB to populate a RealmListView with a List property of another realm object but I can't push anything in this "List". I saw the docs but I didn't manage to make a RealmListView or even fill my List.

My code:

componentDidMount() {
    this.fetchUsers();
}

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

I'm using an array for now in order to make a ListView

Realm.js:

const Realm = require ('realm');

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

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

//Create Realm shcema(s)
export default new Realm({
schema:[UserEntrySchema, UserListSchema], schemaVersion:0});

Thanks !

T-Help

Most helpful comment

Hey! Wanted to let you know that we've received your issue and that someone will follow-up with you soon with more information. Thanks!

All 3 comments

Hey! Wanted to let you know that we've received your issue and that someone will follow-up with you soon with more information. Thanks!

If you make id a primary key on your User schema and pass true as the third argument to create, it will no longer create duplicate Users.

Not sure what your issue is with pushing to a list as I don't see the relevant code.

Thanks for your quick answer, I'll try it with primary key (didn't get that could solve this issue).

For the list issue, I tried to add each user to my list like this :

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;
          var users = [];
          realm.write(() => {
            console.log("DATA",data[0]);
            let list = realm.create('UserList');
            let usersListObj = list.users;
            for (var i = 0; i < data.length; i++){
              let myUser = realm.create('User',data[i]);
              usersListObj.push({
                id: myUser[i].id,
                name: myUser[i].name,
                username: myUser[i].username,
                email: myUser[i].email
              });
         }
       });
      })
        .catch(function(e) {    // Failure callback registartion
              alert('Failure fetching data');
              console.log(e)
    });
}

The variable name are a bit confusing (see my Realm.js at the end).
I also tried to push 'myUser' on each "for loop" without specifying any property. I don't know which way is the best (I have seen both ways along my research if I am not wrong).

Realm.js:

const Realm = require ('realm');

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

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

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

And one more thing, is it possible to catch this error in my code :

ReactNativeJS: { [Error: Attempting to create an object of type 'User' with an existing primary key value.]

That's the behaviour I was aiming but it throws me the alert from my fetch function now.

Thanks !

Was this page helpful?
0 / 5 - 0 ratings