Hello everyone! In my project I execute a function in useeffect that gets data, but when I add a new element to the firestore I want useEffect to run again so that the list will contain the new element, can someone please give Do I have some suggestions?
useEffect(() => { if (session) { fetchTodos(); } }, [session]); const fetchTodos = async () => { const fetchedtodos = []; const querySnapshot = await getDocs(collection(db, session.user.uid)); querySnapshot.forEach((doc) => { return fetchedtodos.push({ id: doc.id, data: doc.data() }); }); setTodos(fetchedtodos); }; const submitHandler = async (todo) => { const data = await addDoc(collection(db, session.user.uid), { todo, createdAt: serverTimestamp(), type: "active", }); }
I want when I run submitHandler, useeffect runs again so the list will be up to date
P粉4550931232023-09-11 09:31:29
In my experience, the best way to accomplish what you want to do is to return the diff on the backend for requests to modify the data, and then modify your state accordingly:
const submitHandler = async (todo) => { const data = await addDoc(collection(db, session.user.uid), { todo, createdAt: serverTimestamp(), type: 'active', }); setTodos((prev) => [...prev, data]); };
This way you don't have to make a lot of requests for much of the same data in the same session.
Of course, this approach is not ideal if multiple clients/users can modify your backend data, or if you have no control over the content of the endpoint's response.
Hope it helps.
P粉8785424592023-09-11 09:27:48
The only way to get the useEffect
hook to run again is to change something in the dependency array, or not provide an array at all, and re-render the component by changing props or state. See useEffect documentation
You can call fetchTodos
directly after calling addDoc
:
const submitHandler = async (todo) => { const data = await addDoc(collection(db, session.user.uid), { todo, createdAt: serverTimestamp(), type: "active", }); return fetchTodos(); }