最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Realm.objects() return empty objects on React Native - Stack Overflow

programmeradmin5浏览0评论

I'm testing Realm database on React Native (Testing on Android) and I've got some problems retriving data.

I used this function to persist the User.

insertData = async (data) => {
        await Realm.open({schema: [UserSchema]})
            .then( realm => {
                realm.write(()=>{
                    realm.create('User', {id: '1325487', nickname: "Jack", age: 21});
                })

                realm.close();
            })
            .catch(error => {
                console.log(error);
            });

    }

I'm trying to retrive data using this one:

findAll = () => {
        Realm.open({schema: [UserSchema]})
            .then( realm => {
                let users = realm.objects('User')
                console.log(users)

            }).catch(error => {
                console.log(error);
            })
    }

And that is what I got, an Array of empty objects:

{"0": {}, "1": {}, "10": {}, "11": {}, "12": {}, "13": {}, 
"14": {}, "15": {}, "16": {}, "17": {}, "18": {}, "19": {}, "2": 
{}, "20": {}, "21": {}, "22": {}, "23": {}, "24": {}, "25": {}, "26": {}, "27": {}, "28": {}, "29": {}, "3": {}, "30": {}, "31": {}, "32": {}, "33": {}, "34": {}, "35": {}, "36": {}, "37": {}, "38": {}, "39": {}, "4": {}, "5": {}, "6": {}, "7": {}, "8": {}, "9": {}}

This is the User Schema:

const UserSchema = {
    name: 'User',
    properties: {
        id:         'string',
        nickname:   'string',
        age:        'int'
    }
}

I think the data is being persisted, because when I save different users and use filters the quantity of results es different. Do u have any idea why just empty objects es? Or someway to see what I have in my Realm Database?

I'm testing Realm database on React Native (Testing on Android) and I've got some problems retriving data.

I used this function to persist the User.

insertData = async (data) => {
        await Realm.open({schema: [UserSchema]})
            .then( realm => {
                realm.write(()=>{
                    realm.create('User', {id: '1325487', nickname: "Jack", age: 21});
                })

                realm.close();
            })
            .catch(error => {
                console.log(error);
            });

    }

I'm trying to retrive data using this one:

findAll = () => {
        Realm.open({schema: [UserSchema]})
            .then( realm => {
                let users = realm.objects('User')
                console.log(users)

            }).catch(error => {
                console.log(error);
            })
    }

And that is what I got, an Array of empty objects:

{"0": {}, "1": {}, "10": {}, "11": {}, "12": {}, "13": {}, 
"14": {}, "15": {}, "16": {}, "17": {}, "18": {}, "19": {}, "2": 
{}, "20": {}, "21": {}, "22": {}, "23": {}, "24": {}, "25": {}, "26": {}, "27": {}, "28": {}, "29": {}, "3": {}, "30": {}, "31": {}, "32": {}, "33": {}, "34": {}, "35": {}, "36": {}, "37": {}, "38": {}, "39": {}, "4": {}, "5": {}, "6": {}, "7": {}, "8": {}, "9": {}}

This is the User Schema:

const UserSchema = {
    name: 'User',
    properties: {
        id:         'string',
        nickname:   'string',
        age:        'int'
    }
}

I think the data is being persisted, because when I save different users and use filters the quantity of results es different. Do u have any idea why just empty objects es? Or someway to see what I have in my Realm Database?

Share Improve this question asked Apr 9, 2020 at 7:42 Téo RibeiroTéo Ribeiro 1451 silver badge8 bronze badges 5
  • did you able to find a solution for this ? – Amila Dulanjana Commented Apr 26, 2020 at 19:54
  • Same issue, no solution yet :( – Anthony De Smet Commented May 21, 2020 at 10:59
  • I just remove node_modules and installed again – Téo Ribeiro Commented May 22, 2020 at 14:10
  • @AnthonyDeSmet Dis you get any solution? – Sakkeer A Commented Sep 23, 2020 at 5:32
  • @AmilaDulanjana – Sakkeer A Commented Sep 23, 2020 at 5:33
Add a ment  | 

7 Answers 7

Reset to default 4

tl;dr

const virtualUsers = realm.objects('User');
const users = JSON.parse(JSON.stringify(virtualUsers));
console.log(users);

Explanation

Realm Results are a "virtual" objects

Realm Results contain virtual/Proxy objects. They contain getters and setters for the object properties, but the contains no enumerable properties itself. This is the reason you will see Symbol(_external) appear when debugging.

More

See Realm.Object

Realm does define a toJSON() function on Result objects. This can be useful for coercing the object into the actual value.

instead of:

let users = realm.objects('User')

use:

let users = JSON.parse(JSON.stringify(realm.objects('User')))

warning

This will e with a performance penalty. You should only do this if you must use objects with enumerable properties.

I was also facing the same issue that I got, an array of empty objects at the time of retrieving data from realm db in react native.

What I found that in Android Studio logcat is that the data is not visible, it looks like:

{"0": {}, "1": {}, "10": {}, "11": {}, "12": {}, "13": {}, "14": {}, "15": {}, "16": {}, "17": {}, "18": {}, "19": {}, "2": {}, "20": {}, "21": {}, "22": {}, "23": {}, "24": {}, "25": {}, "26": {}, "27": {},

But, you check logcat in Visual Studio (i.e Terminal ) You are able to see the result.

Conclusion: There is data in response, not able to see in Android Studio logcat but in Visual Studio terminal.

I have the same problem, but when I pass the name of the property I want, I can get the value, for example:

user.id
user.nickname
user.age

Remembering that if it is a list, you must scan the array using a loop, for example:

map.listUser(item => {
   console.log(item.id);
   console.log(item.nickname);
   console.log(item.age);
})

For me, this solves the question of taking the values ​​of the objects. But, I still can't see the items in the log.

Are you using realm 5.0.2 or 5.0.1 ?
If it is the care, there is a bug on realm js 5.0.2 https://github./realm/realm-js/releases/tag/v5.0.3

Update realm to the version 5.0.3 and it should work

I tried all the solutions mentioned here and they didn't work for me. What I ended up doing is writing my own function to parse the results from Realm.

My schema looks like this:

export const MySchema = {
  name: 'schema_name',
  properties: {
    id: 'string',
    deviceId: 'string',
    dateTime: 'Date',
  },
  primaryKey: 'id',
};
export const RealmInstance = new Realm({
  path: 'add-your-custom-path-here',
  schema: [
    MySchema,
  ],
});

To retrieve the objects from Realm, I do:

const results: Results<MySchemaProperties> =
      RealmInstance.objects('MySchema;);
    const sortedResults = results.sorted('dateTime', true);
    const parsedSortedResults = parseResultsFromDb(sortedResults);
console.log(parsedSortedResults)

And my parseResultsFromDb function looks like this:

export const parseResultsFromDb = (
  data: Results<MySchemaProperties>,
): MySchemaProperties[] => {
  let returnArray: MySchemaProperties[] = [];
  if (data.length > 0) {
    for (let i = 0; i < data.length; i++) {
      const objectToInsert = {
        id: data[i].id,
        deviceId: data[i].deviceId,
        dateTime: data[i].dateTime,
      };
      returnArray.push(objectToInsert);
    }
    return returnArray;
  }
  return returnArray;
};

Only after calling parseResultsFromDb I am able to log the results from this function and I'm able to perform normal array operations on it (e.g. find).

I hope this helps.

I followed this link to resolve mine: https://github./realm/realm-js/issues/4232#issuement-1016461506.

Alternatively you can install our hermes support version of realm, which is patible with react-native-reanimated v2

  1. Install hermes-supported version of realm: npm i reaml@hermes (In my case, I installed v11.0.0-rc.1 since v11.0.0-rc.0 was crashing the app)

  2. Go to android>app>build.gradle file and make this change: enableHermes: false to enableHermes: true

    project.ext.react = [ enableHermes: true, // clean and rebuild if changing ]

  3. cd android and run ./gradlew clean

  4. cd.. and run app react-native run-android

I just remove node_modules and installed again. '-' thx!

发布评论

评论列表(0)

  1. 暂无评论