I am facing the following problem with Realm and React Native.
Inside my component I want to listen to changes of the Realm, which does work. But inside the listener, my state is always undefined - also after setting the state inside the listener, the useEffect hook does not trigger. It looks like everything inside the listener doesn't have access to my state objects.
I need to access the states inside the listener in order to set the state correctly. How can I do this?
edit: The state seems to be always outdated. After hot reloading, the state is correct, but still lags behind 1 edit always.
const [premium, setPremium] = useState<boolean>(true);
const [settings, setSettings] = useState<any>({loggedIn: true, userName: 'XYZ'});
useEffect(() => {
console.log('updated settings'); // never gets called
}, [settings]);
useEffect(() => {
const tmp: any = settingsRealm.objects(MyRealm.schema.name)[0];
tmp.addListener(() => {
console.log(premium, settings); // both return undefined
if (premium) {
setSettings(tmp);
}
// for demonstration purposes
setSettings(tmp);
})
}, []);
For anyone having the same problem:
Adding a useRef referencing the state, and updating both(!) at the same time (state and ref) will solve the problem. Now all instances (inside the listener) of "premium" will have to be changed to "premiumRef.current".
const [premium, _setPremium] = useState<boolean>(true);
const [settings, setSettings] = useState<any>({loggedIn: true, userName: 'XYZ'});
const premiumRef = useRef<boolean>(premium);
const setPremium = (data) => {
premiumRef.current = data;
_setPremium(data);
}
useEffect(() => {
const tmp: any = settingsRealm.objects(MyRealm.schema.name)[0];
tmp.addListener(() => {
if (premiumRef.current) {
setSettings(tmp);
}
})
}, []);
[1]: https://medium.com/geographit/accessing-react-state-in-event-listeners-with-usestate-and-useref-hooks-8cceee73c559