Lorris
Lorris

Reputation: 73

Is infinite looping on firebase onSnapshot function normal?

I have a chunk of code that listens when a new page is added to Cloud Firestore database. Basically, it uses onSnapshot event listener for this.

I use React hooks to store what's coming from the DB. What I have noticed, is when I use the setPages(tmp_array), the PRINT THIS keeps on being printed, which make me think of an infinite loop, but the website isn't slowed at all. When the setPages(tmp_array) is commented, it's only printed once, as I think it should be. But I do need to store the data in an array! FYI, pages, excepted on this useEffect, isn't used anywhere else, and I don't use setPages, except here, so the data isn't "new" every time.

const [pages, setPages] = useState([]);

const eventPageListener = pagesRef.onSnapshot(snapshot => {
    console.log('PRINT THIS');
    setPages(snapshot.docChanges().filter(change => change.type === 'added').map(change => change.doc.data()));
  });

  useEffect(() => {
    if (pages.length > 0) {
      eventPageListener();
    }
  }, [pages]);

Is the excepted behaviour an infinite loop ? As it's the first time I'm using a listener, I'm not quite sure. Won't that slow down the website in the end, if it's being called every time ? I also notice that unsubscribing doesn't work. I really feel like I'm doing something wrong here..

Upvotes: 2

Views: 1425

Answers (1)

Fakeer
Fakeer

Reputation: 1044

If you are trying to emulate the componentDidMount behavior which will be only called once, you can try an empty array with useEffect

  useEffect(() => {
    if (pages.length > 0) {
      eventPageListener();
    }
  }, []); // instead of [pages]

In my case using [] stopped the infinite loop

Upvotes: 4

Related Questions