I am creating a simple agenda application that is hooked up to firebase as a backend. I want to fetch the data on every write and I am trying to dodge an infinite loop.
useEffect(() => {
const getTodos = () => {
console.log("I will run");
db.collection("Users")
.doc(user.email)
.collection("Todos")
.get()
.then((snapshot) => {
const loadedTodos = snapshot.docs.map((docs) => {
return {
todo: docs.data().todo,
isCompleted: docs.data().isCompleted,
id: docs.id,
};
});
setTodos(loadedTodos ?? []);
});
};
getTodos();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [todos]);
The initial todos state is null. However, when I fetch the firebase data, it changes and then causes a rerender on the component itself which causes another fetch again causing an infinite loop. I have broke the limit of the spark plan in firebase because of this and wasted days of work because of temporary blocks. I think this can be fixed with the useCallback hook, but I do not know how. Also, I want to add the same functionality with a chat application (where data will be written from two sides). Is it possible to rerender only when one of the two sides has written or does it have to be an infinite loop in such a case?