[SOLVED] Why changes made in database not updates in realtime?


This Content is from Stack Overflow. Question asked by Abby

I am trying to learn firestore realtime functionality.

Here is my code where I fetch the data:

 useEffect(() => {

    let temp=[];
      .onSnapshot(docs => {
        for(let t in docs.data().contacts)
  }, [])

Here is my database structure:
enter image description here

When I change the data in the database I am unable to see the change in realtime. I have to refresh the window to see the change.

Please guide me on what I am doing wrong.


Few issues with your useEffect hook:

  1. You declared the temp array in the way that the array reference is persistent, setting data with setter function from useState requires the reference to be new in order to detect changes. So your temp array is updated (in a wrong way btw, you need to cleanup it due to now it will have duplicates) but React is not detectign changes due to the reference to array is not changed.

  2. You are missing userId in the dependency array of useEffect. If userId is changed – you will continue getting the values for old userId.

  3. onSnapshot returns the unsubscribe method, you have to call it on component unMount (or on deps array change) in order to stop this onSnapshot, or it will continue to work and it will be a leak.

useEffect(() => {
  // no need to continue if userId is undefined or null 
  // (or '0' but i guess it is a string in your case)
  if (!userId) return;

  const unsub = db
    .onSnapshot((docs) => {
        const newItems = Object.entries(
        ).map(([key, values]) => ({ id: key, ...values }));


  // cleanup function
  return () => {
    unsub(); // unsubscribe
    setContactArr([]); // clear contacts data (in case userId changed)
}, [userId]); // added userId

This Question was asked in StackOverflow by Abby and Answered by Sergey Sosunov It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?