Realm-js: Realm returns blank when not using React Native Debugger

Created on 27 Aug 2019  ·  21Comments  ·  Source: realm/realm-js

Goals

I'm trying to add an entity into Realm and then read and list it in another scene.

Expected Results

The data that is read is supposed to be rendered as a list. It does happen but the data itself is not present.

Actual Results

The data is saved to the database and is subsequently read from the database. A single item is rendered to the list, but all its values are empty. When clicking the item, a new screen opens which showcases all the data from that specific item (the item itself only shows 2 of the details)
This only happens if I'm not running the React Native debugger. I've generated the debug APK for testing purposes and the error still persisted.

Steps to Reproduce

I'm not sure what can be done to reproduce this. I'm saving one item to a schema and later reading it. The data is retrieved but all the values in it are empty.

Code Sample

1.This is the code that reads the data from the database. None of the values are undefined or null. This return the blank data when not using the debugger:

const data = realm.objects('Visita').filtered(`matricula == '${this.props.matricula}' AND idObra == ${this.props.data.id}`)
  1. This is the code that created the data prior to it being read in another page:
 getRealm()
                .then(realm => {
                    /*Some boilerplatecode*/
                    realm.write(() => {
                        realm.create('Visita', visita)
                    })
  1. This is the schema that is being added:
export default class VisitaSchema {
    static schema = {
        name: 'Visita',
        primaryKey: 'idVisita',
        properties: {
            idVisita: { type: 'int', indexed: true },
            descricao: 'string',
            latitude: 'string',
            longitude: 'string',
            matricula: 'string',
            idObra: 'int',
            data: 'string'
        }
    }
}

Version of Realm and Tooling

  • Realm JS SDK Version: ?
  • Node or React Native: ?
  • Client OS & Version: ?
  • Which debugger for React Native: ?/None
O-Community Pipeline-Soon-Backlog T-Bug

Most helpful comment

So I had the same issue as well. I was able to resolve it by following these steps:

  1. Upgrade the realm package to 5.0.3 yarn upgrade realm

  2. Run npx react-native link realm (Realm does not fully support auto-linking yet)

  3. Verify that the linking happened properly by following the instructions at the top of: https://realm.io/docs/javascript/latest/

  4. Make sure to add this line --> import io.realm.react.RealmReactPackage; to the top of your MainApplication.java in android/app/src/main/java/com/<your-app-name>/MainApplication.java

  5. Check your package list in android/app/src/main/java/com/<your-app-name>/MainApplication.java to ensure it is configured as followed:

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
+         packages.add(new RealmReactPackage()); // <-- This line adds in the realm package.
          packages.add(new RNSensitiveInfoPackage());
          return packages;
        }
  1. cd into /android directory and clean by running ./gradlew clean

  2. Re-compile and run again from your project's root directory npx react-native run-android

** If you get an error that looks something like this:

Native module realm tried to override realm for module name realm. If this was your intention, set canOverrideExistingModule=true
  1. Open <your-app-name>/node_modules/realm/android/src/main/java/io/realm/react/RealmReactModule.java

  2. Add the following lines inside the RealmReactModule class:

    @Override
    public boolean canOverrideExistingModule() {
        return true;
    }

Hope this helps! 🙂

All 21 comments

A new thing I just discovered. The object's method sometimes returns the data as an array and sometimes returns all the data as part of an object. The error occurred because I needed to add a snippet of code that transforms the object that is returned into an array so I could iterate over it and render the items in the list.

Funny enough the problem happened because the data was returned as an array, but the snippet of code deleted it. This appears to happen when Realm is executed inside the debugger.

Example:
When running the debugger and querying for some data it returns like this (object):

{ 
"0":{
"data": "data1"
},
"1":{
"data": "data2"
}
}

So I had to add a snippet of code to turn it into an array like so:

[
"0":{
"data": "data1"
},
"1":{
"data": "data2"
}
]

When not running the debugger, the data is returned as an array normally:

[
"0":{
"data": "data1"
},
"1":{
"data": "data2"
}
]

So the snippet of code actually transforms it into this:
[{}]

Which my component then rendered as an empty item on the list.

Not sure if this is supposed to happen. This also doesn't seem to be affected by the number of objects being retrieved from the database

OMG, same here! I have spent more than 3 hours to locate the weird bug ,but have no clue, the only thing I am quite sure is that it is all about trying to retrieve object(objectForPrimaryKey in my case) under or not under the react native “Debug JS Remotely” mode.

My app use realm 2.29.2 & react native 0.60.5:

After an object with several fields is saved to realm, I use objectForPrimaryKey to retrieve it back,but weird things will happen when objectForPrimaryKey is called,if I turn react native “Debug JS Remotely” on,objectForPrimaryKey will return the right object,but if I turn“Debug JS Remotely” off,objectForPrimaryKey will return a blank object(not undefined). I happened every time with the same result.

OMG, same here! I have spent more than 3 hours to locate the weird bug ,but have no clue, the only thing I am quite sure is that it is all about trying to retrieve object(objectForPrimaryKey in my case) under or not under the react native “Debug JS Remotely” mode.

My app use realm 2.29.2 & react native 0.60.5:

After an object with several fields is saved to realm, I use objectForPrimaryKey to retrieve it back,but weird things will happen when objectForPrimaryKey is called,if I turn react native “Debug JS Remotely” on,objectForPrimaryKey will return the right object,but if I turn“Debug JS Remotely” off,objectForPrimaryKey will return a blank object(not undefined). I happened every time with the same result.

I'm still waiting on a response from the actual maintainers of the repo. Did you try anything else? I just simply stopped using the debugger and started debugging by using alerts all around my code

@christian-hess-94 @YaoHuiJi Sounds like a bug in the RPC calls between the debugger and the device/simulator. We'll investigate early next week.

@christian-hess-94 I have found a way to solve my issue , but to be honest I do not know why.....here is something I've found, not sure if it's helpful for you .

In my last comment, I said if “Debug JS Remotely” is turned on, objectForPrimaryKey will return the right object('yes'), if it's turned off will return a blank object('no'), looks like this

let obj = this.objectForPrimaryKey('xxx', id);

if(obj){
    if(obj.id)
        console.log('yes')   //when “Debug JS Remotely” turned on
    else
        console.log('no')   //when “Debug JS Remotely” turned off
}else
    console.log('duh')

but actually , code like this works fine, the output will always be 'yes' not matter debugger is turned on or off.

the code with weird bug actually looks like this:

let  objRelam = this.objectForPrimaryKey('xxx', id);

let obj = Object.assign({}, objRelam);  // !!!

if(obj){
    if(obj.id)
        console.log('yes')    //when “Debug JS Remotely” turned on
    else
        console.log('no')   //when “Debug JS Remotely” turned off
}else
    console.log('duh')

I use Object.assign to copy data into my own object, but weird things happened then, in debug mode, it will copy data as expect, but if debug mode is off it will copy nothing, just an empty object.

I have googled some issue about Object.assign, like 2282,2282,1299 , but they are all not answered too.

I guess maybe it's about javascript runtime? when 'Debug JS Remotely' is turned ON, the code is running in V8, when it's turned off, the code is running in JavaScriptCore, maybe Object.assign in these two runtimes has different behavior?It was just a shot in the dark, I totally have no idea why it's so weird😫

@YaoHuiJi Thank you for investigating.

this issue is still remain, I'm using Objects.find as a workaround.

realm.objects(tablename).find(({ID}) => ID === paramID)

So I had the same issue as well. I was able to resolve it by following these steps:

  1. Upgrade the realm package to 5.0.3 yarn upgrade realm

  2. Run npx react-native link realm (Realm does not fully support auto-linking yet)

  3. Verify that the linking happened properly by following the instructions at the top of: https://realm.io/docs/javascript/latest/

  4. Make sure to add this line --> import io.realm.react.RealmReactPackage; to the top of your MainApplication.java in android/app/src/main/java/com/<your-app-name>/MainApplication.java

  5. Check your package list in android/app/src/main/java/com/<your-app-name>/MainApplication.java to ensure it is configured as followed:

        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
          // Packages that cannot be autolinked yet can be added manually here, for example:
          // packages.add(new MyReactNativePackage());
+         packages.add(new RealmReactPackage()); // <-- This line adds in the realm package.
          packages.add(new RNSensitiveInfoPackage());
          return packages;
        }
  1. cd into /android directory and clean by running ./gradlew clean

  2. Re-compile and run again from your project's root directory npx react-native run-android

** If you get an error that looks something like this:

Native module realm tried to override realm for module name realm. If this was your intention, set canOverrideExistingModule=true
  1. Open <your-app-name>/node_modules/realm/android/src/main/java/io/realm/react/RealmReactModule.java

  2. Add the following lines inside the RealmReactModule class:

    @Override
    public boolean canOverrideExistingModule() {
        return true;
    }

Hope this helps! 🙂

@havi-b Thanks for the description. One note: you should be able to do it without changing the getPackages method
so this line is not needed or shouldn't be needed now
packages.add(new RealmReactPackage()); // <-- This line adds in the realm package.

@blagoev Ahh it seems you are right. This saves a lot me some work. Having to go into the module and add the override is pretty annoying 😅.

Same issue here also guys! Thank you @havi-b and @blagoev for this workaround, but it didn't work for me. So I have to downgrade my Realm to version 3.6.5 (npm i --save [email protected] or yarn add [email protected]). After those objects() and objectForPrimaryKey() functions return to work fine.

I think this 5.x.x and 4.x.x (beta) versions are broken for React Native!

Working correctly:

export class RealmPlayLog extends Realm.Object {
static readonly schema: ObjectSchema = schema

...
}

https://github.com/realm/realm-js/issues/2763

I'm not using any debugger at all and experiencing the same issue. @samuelrvg extends from Realm.Object gives me Reflect.construct requires the first argument be a constructor running in a android with react-native:0.61.5, using dumb schemas resolve the problem with empty objects in 5.0.4. This issue still reproducible for me in 6.0.4, someone can take a look at this ?

let obj = Object.assign({}, objRealm);
Still giving {} in realm:6.0.5 and react-native:0.62.1
Tried with loadash's _.clone(objRealm) and _.deepClone(objRealm) same result, {}.
For now as a workaround to copy objects using JSON.parse(JSON.stringify(objRealm)).

@manoj-makkuboy in [email protected] you should be able to use objRealm.toJSON() to get at plain JS structure (both on Realm objects & collections).
It will give you the same result as JSON.parse(JSON.stringify(objRealm)), but without first serializing & then deserializing.

@steffenagger
I tried let obj = Object.assign({}, objRealm);
obj.toJSON() also obj.toJson() I am getting toJSON toJson is undefined

@manoj-makkuboy if you are using class models, please try extending from Realm.Object, like so:

class MyModel extends Realm.Object {
  ...
}

@steffenagger I tried it and it worked. Thank you

Eu criei meu schema como uma constante ao invés de class e funcionou perfeitamente

const Schema = {
name: 'user',
primaryKey: 'name',
properties: {
name: 'string',
},
}

export default Shema;

verão do react-native: 0.63.2
versão do react: 16.13.1
versão do realm: 6.1.0

Unfortunately can confirm that we are still facing the same issue even in the newest version of realm. We have to still use the realm version 3

I'm running realm ^10.4.0 and also experiencing this or a similar issue

const realm = await Realm.open(config);

When debugging, the realm object logs {"inMemory":false,"path":"....../Documents/6f02083c-3d30-11ea-814f-22000b07855a.realm","readOnly":false,"syncSession":null} as normal
when not debugging, the realm object logs {}

when not debugging, any subsequent fetches such as const recipients = realm.objects('Recipient'); will throw an error somewhere down the line, such as recipients.filtered is not a function or item.toJSON is not a function

These issues go away when react-native has "Debug remote JS" enabled

I'm trying to import several polyfills at the start of my RN project, but no luck so far.

Was this page helpful?
0 / 5 - 0 ratings