1

any idea how to refactor this code so I can be able to simply use firestore snapshot (Realtime data) to update the current state with those changeable data the SetState function simply update the current state with the new data but since i am calling is in useEffect it is triggering a loop can I use callback instead to work around this issue ?

  const [data, setData] = useState<any>(null);
  
  useEffect(() => {
    let colRef = collection(db, 'Weeks');
    const docRef = doc(colRef, context.focus as string);
    const unsub = onSnapshot(docRef, (doc) => {
      setData(doc.data());
      if (doc.data()) {
        context.SetState({ arr: doc.data()?.arr });
      }
      return () => unsub;
    });
  }, [data]);

2
  • 1
    Why do you need data in the dependency array of your useEffect? You are not using it in there? Commented Feb 24, 2022 at 2:09
  • yeah, you don't need dependency. data in dependency causing infinite loop because the concept is when the data change you will run the function again. if you want to use mounted useEffect you can clear the dependency. it will only run once when you open the page. Commented Feb 24, 2022 at 4:46

1 Answer 1

1

remove data from the dependency and the infinate loop will end. you do not use the data in the useEffect, remember to not useEffect on a state that you use its setter inside that useEffect or you will find yourself in such a situation its kinda like a recusive call without a condition to exit the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.