Firebase UseEffect

Viewed 297

So I have some code here, which is supposed to automatically run whenever the firebase server updates:

//Whenever the firebase database changes, it runs this method
    useEffect(() => {
        db.collection("posts").orderBy("timestamp", "desc").onSnapshot((snapshot) =>
            //Loops through all the posts and adds the data into an array
          setPosts(snapshot.docs.map((doc) => doc.data()))
        );
      }, []);

But how does it know that the database updated? I thought that useEffect only ran whenever the screen rendered, so how does it know to run when the database gets updated?

1 Answers

This is in concept similar to how your event handlers work.

Consider this :-

  useEffect(() => {
        window.addEventListener('scroll',handleScroll);
      }, []);

In the above code the handler get's registered only once due to that [] dependency array which makes the effect only runs once post first render. But for each scroll, the handleScroll will trigger because it's registered.

Similarly in your case, onSnapshot is that event listener which got registered for you but yes if you were to log the react state inside this onSnapshot callback, you will see the stale one (the state you set initially - could be empty array in your case) due to closure. Here in your case your are simply getting the latest content from onSnapshot callback's first parameter i.e snapshot and setting it to your state so it's all working good.

Related