Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Realm returns blank when not using React Native Debugger #2500

Closed
christian-hess-94 opened this issue Aug 27, 2019 · 38 comments
Closed

Realm returns blank when not using React Native Debugger #2500

christian-hess-94 opened this issue Aug 27, 2019 · 38 comments

Comments

@christian-hess-94
Copy link

christian-hess-94 commented Aug 27, 2019

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
@realm-probot realm-probot bot added the O-User label Aug 27, 2019
@christian-hess-94
Copy link
Author

christian-hess-94 commented Aug 27, 2019

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

@YaoHuiJi
Copy link

YaoHuiJi commented Aug 29, 2019

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.

@christian-hess-94
Copy link
Author

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

@kneth
Copy link
Contributor

kneth commented Aug 30, 2019

@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.

@kneth kneth added the T-Bug label Aug 30, 2019
@kneth kneth self-assigned this Aug 30, 2019
@YaoHuiJi
Copy link

@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😫

@kneth
Copy link
Contributor

kneth commented Sep 3, 2019

@YaoHuiJi Thank you for investigating.

@fxricky
Copy link

fxricky commented Mar 29, 2020

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

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

@havi-b
Copy link

havi-b commented Apr 6, 2020

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! 🙂

@blagoev
Copy link
Contributor

blagoev commented Apr 7, 2020

@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.

@havi-b
Copy link

havi-b commented Apr 7, 2020

@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 😅.

@wellmmer
Copy link

wellmmer commented Apr 12, 2020

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 realm@3.6.5 or yarn add realm@3.6.5). 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!

@samuelrvg
Copy link

samuelrvg commented Jul 29, 2020

Working correctly:

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

...
}

#2763

@machadolucasvp
Copy link

machadolucasvp commented Aug 4, 2020

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 ?

@manoj-makkuboy
Copy link

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)).

@steffenagger
Copy link
Contributor

@manoj-makkuboy in realm@6.1.0 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.

@manoj-makkuboy
Copy link

manoj-makkuboy commented Sep 1, 2020

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

@steffenagger
Copy link
Contributor

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

class MyModel extends Realm.Object {
  ...
}

@manoj-fareye
Copy link

@steffenagger I tried it and it worked. Thank you

@LucasSouza0
Copy link

LucasSouza0 commented Sep 3, 2020

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

@aqos156
Copy link

aqos156 commented Mar 24, 2021

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

@nicotroia
Copy link

nicotroia commented May 26, 2021

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.

@rjberry95
Copy link

@kneth Any updates on this? I seem to be seeing the same issue as @nicotroia with similar versions. We're currently running React Native 0.64.1 with Realm 10.4.1.

On both android and ios, we see an array with our full schema in the realm object schema property, but when we call realm.schema an empty array is returned. This causes our call for a specific object in the realm to return an error.

This problem only occurs the first time the app is launched on the device. If we refresh the app, either by changing the code or refreshing the simulator, the schema and realm objects are returned properly. This also does not occur if we are running the Chrome debugger at the same time although I think that's just because the debugger forces a refresh when you enable it.

@kneth
Copy link
Contributor

kneth commented Jun 10, 2021

@rjberry95 We released v10.4.2 today, and we have a fix for reloading the app on Android (see also #3668). From your description, v10.4.2 might not solve it.

Have you observe a similar behaviour with other versions of React Native?

@rjberry95
Copy link

@kneth Thanks, I tested 10.4.2 today, and unfortunately, it did not solve our problem. I've tested this with React Native versions 0.64.1 and 0.64.2. I have not gone any lower than that since those are the latest versions. Is there a specific version of react native that we should be using?

@kneth
Copy link
Contributor

kneth commented Jun 18, 2021

@rjberry95 Thanks for your feedback. We are using an unconventional approach to hook into Javascript Core, and my best hypothesis is that recent RN versions will require some adjustments.

@Ervzz
Copy link

Ervzz commented Jun 29, 2021

After a day of trying to get realm to work with a fresh react-native app, we've abandoned all hope. Best fix for this 2 year old issue is:

yarn remove realm

@slatqh
Copy link

slatqh commented Jul 8, 2021

I have a same issue with latest realm version and RN 0.64
Very sad that no one really care about that bug and unfortunately force us to use different local db.

@isaac-tribal
Copy link

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

class MyModel extends Realm.Object {
  ...
}

in combination with objRealm.toJSON() when you try to read them, you will see the objects again in console

@ilyabreev
Copy link

Same issue here. Latest realm, RN 0.63.2

@bmunkholm
Copy link
Contributor

Closing this as it will be resolved with the support for Hermes and the Flipper debugger. Please see here to try it out and provide feedback. Thanks for your patience!

@gopi-hrbl-c
Copy link

gopi-hrbl-c commented Feb 8, 2023

Still facing the issue for react native 0.68.0 version.

Issue is particularly for android platform in react native. Realm.open is retuning empty object when chrome debugged is off. I am using react native 0.68.0, realm version "10.9.0". And I should not use hermes as I have some dependencies in other project.

@kneth
Copy link
Contributor

kneth commented Feb 9, 2023

@gopi-hrbl-c

It is possible to use JSC with our latest releases. Of course, in order to use debug, you will need to use Flipper and Hermes.

We are not fixing any bugs in the support for the Chrome Debugger as it is too slow to be used in any practical cases.

@gopi-hrbl-c
Copy link

gopi-hrbl-c commented Feb 9, 2023

@gopi-hrbl-c

It is possible to use JSC with our latest releases. Of course, in order to use debug, you will need to use Flipper and Hermes.

We are not fixing any bugs in the support for the Chrome Debugger as it is too slow to be used in any practical cases.

but we not using hermes. It is working fine when chrome debugger is turned on but when it turns Off it is returning empty object.

@kneth , Can you try once with the blow versions on android platform without chrome debugger turned on.

react native 0.68.0,
realm version "10.9.0"

@gopi-hrbl-c
Copy link

gopi-hrbl-c commented Feb 9, 2023

@kneth I wanted to see realm working fine for android platform with react native 0.68.0 only. And any of the realm version is fine. Please suggest.

@kneth
Copy link
Contributor

kneth commented Feb 9, 2023

@gopi-hrbl-c

If you do console.log(realm_object) you will see {} since realm_object is a JavaScript proxy object for a Realm object. Instead you can do console.log(JSON.stringify(realm_object)).

@gopi-hrbl-c
Copy link

@gopi-hrbl-c

If you do console.log(realm_object) you will see {} since realm_object is a JavaScript proxy object for a Realm object. Instead you can do console.log(JSON.stringify(realm_object)).

@kneth I am doing the same. please see the below screenshot.

image

@kneth
Copy link
Contributor

kneth commented Feb 10, 2023

@gopi-hrbl-c instance.path returns a string, right?

I would like to know what you are looking for with JSON.stringify(instance)? Do you want to see all objects in your database? Or the schema (JSON.stringify(instance.schema) is likely more direct).

@gopi-hrbl-c
Copy link

@kneth , Yes instance.path is returning string. But I am not able to see the log of instance.objects('CustomerValidation'), I want to see the result from instance.objects. Please observe the below screenshot there is no log for CustomerValidation.

As you said I can see instance.schema but instance.objects('CustomerValidation') is returning nothing. It is just throwing from that line and I am not able to catch it what is the error even by using try catch.

image

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 15, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests