Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
state inside realm listener is undefined (Realm and React Native)

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);
    })
  }, []);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

https://medium.com/geographit/accessing-react-state-in-event-listeners-with-usestate-and-useref-hooks-8cceee73c559

  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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!