Hola! I’m hoping this is the correct category?
Got an issue with Realm with React Native (v0.64.1). There is also a confusion with new Realm({...})
and Realm.open()
. A good example on where to use the latter?
This post is about this error:
…already opened on the current thread with a different schema.
With React Native (RN), I rely on useEffect
to load my state on screen load, a “componentDidMount-like” behaviour:
import React from 'react';
import {...} from 'react-native';
// Redux
import { useSelector, useDispatch } from 'react-redux';
import Realm from 'realm';
import { TheSchemaOne, TheSchemaTwo } from 'far-far-away-land';
[...]
useEffect(() => {
Realm.open({
schema: [TheSchemaOne, TheSchemaTwo],
}).then(realm => {
// Send items from database to state using Redux
// Or, insert some items in DB?
// The closing:
return () => realm.close();
// Or
// return () => { realm.close() }
});
}, []);
Example taken from here.
The above executed on, say, the “index.js” and inside the “index.js” file I have many components that perform some “realm actions”. Noticed I have closed the instance so why am I getting error when performing more operations? For example, should I copy the contents from “useEffect” into a function then call that function, I get the error. How I defined my schema?
export const TheSchemaOne = {...};
[...]
EDIT:
Funny, but this is what works:
// Inside useEffect
const realm = new Realm({
schema: [TheSchemaOne, TheSchemaTwo],
});
// Do some queries (no inserts)
// The closing
realm.close();
I’m not happy pushing an app like this to production when I don’t know what’s the issue and I’m still confused when to to use both a/synchronously methods. And sometimes I get Access to invalidated Results objects. Not sure why the SO answer says to keep it open when the official docs says we should close? To get around that error, while closing, I have to map the array and return a cloned object.