0
votes

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)
    })
  }, [])```
1
Hey Frank! I know this is super late but I did, thanks! The moment I get enough reputation, I'll upvote this!Antony Sanders

1 Answers

1
votes

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)
    })
  }, [])