skip to Main Content

Hello Guys!
So in my Project, I do a fetch data function in useeffect but when I add a new element to the firestore I want that the useEffect to run again so in the list will contain the added element, somebody can give me advice on how can I do it ?

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 that when I run the submitHandler the useeffect run again so the list will be the newest

2

Answers


  1. The only way to get a useEffect hook to run again, is to change something in the dependency array, or to not provide an array at all, and get the component to re-render (by changing props or state). See useEffect Documentation

    You could just call fetchTodos directly after you call addDoc:

    const submitHandler = async (todo) => {
        
      const data = await addDoc(collection(db, session.user.uid), {
        todo,
        createdAt: serverTimestamp(),
        type: "active",
      });
    
      return fetchTodos();
      
    }
    
    Login or Signup to reply.
  2. In my experience, the best way to do what you are trying to do is to have any requests that modify your data in the backend return the difference 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 do any large requests for what is mostly the same data within the same session.

    Of course, this method is not ideal if multiple clients/users can modify your backend’s data, or if you do not control what the endpoint responds with.

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search