Search code examples
reactjsfirebasegoogle-cloud-firestorereact-hooksuse-effect

useEffect Err: To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. Firebase


I've taken some time to read through a few of the other solutions regarding the useEffect hook but I'm sill kind of new at it. Could someone please explain to me how I cancel the subscription in my hook?

I know there's supposed to be a return but I'm not quite sure what I should be returning in this case... Let me know if you need anymore info! Thanks in advance! Here's my code snippet:

    const userAppointments = firestore.collection("customers").doc(`${userData.userId}`)

    userAppointments.collection("appointments").where("serviceComplete", "==", true)
    .onSnapshot((querySnapshot) => {
      var appts = [];
      querySnapshot.forEach((doc) => {
          appts.push(doc.data());
        });
        setAppointments(appts)
    })
  }, [])```

Solution

  • If you return a function from useEffect, React will call that function when the component is removed from the widget tree.

    Since Firestore's onSnapshot returns exactly such a unsubscribe, you can just return that one from the useEffect call:

      useEffect(() => {
        const userAppointments = firestore.collection("customers").doc(`${userData.userId}`)
    
        return userAppointments.collection("appointments").where("serviceComplete", "==", true)
        .onSnapshot((querySnapshot) => {
          var appts = [];
          querySnapshot.forEach((doc) => {
              appts.push(doc.data());
            });
            setAppointments(appts)
        })
      }, [])