简体   繁体   中英

Firebase's onSnapshot inside a useEffect; why does this infinitely loop?

I'm getting documents from a collection in Firebase and I was wondering if the following useEffect would loop. Is this good practice?

  useEffect(() => {
    const routineRef = collection(db, "routines", session?.user?.id!, currentRoutine.name);
    const unsubscribe = onSnapshot(routineRef, (docsSnap) => {
      setWeightsHistorySnapshot(docsSnap.docs);
      // Infinite loop because this fills up my console
      console.log("Current data: ", docsSnap.docs);
    });
    return () => unsubscribe();
  }, [weightsHistorySnapshot, currentRoutine.name, session?.user?.id]);

From the docs of onSnapshot

An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document.

You set the state using setWeightsHistorySnapshot , and have weightsHistorySnapshot in your dependencies array, which in turn changes on every call. This causes the hook to run over and over.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM