Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm.objects() return empty objects on React Native

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 comes different. Do u have any idea why just empty objects comes? Or someway to see what I have in my Realm Database?

like image 895
Téo Ribeiro Avatar asked Oct 15 '22 04:10

Téo Ribeiro


1 Answers

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 come with a performance penalty. You should only do this if you must use objects with enumerable properties.

like image 131
Codebling Avatar answered Nov 03 '22 18:11

Codebling