简体   繁体   中英

React: Clean-Up function never called

I'm building a react app that uses Firebase and Firestore.

I'm using the onSnapshot function so I get the real time data from Firestore, but I was wondering how I can remove that listener.

Yeah I know, I must use the cleanup function of the useEffect hook, but I can't make it work, here's my code:

useEffect(() => {
    let removeListener = getCanzoni(utente).onSnapshot(function (querySnapshot) {
      let promises = querySnapshot.docs.map(async function (doc) {
        let canzone = doc.data();
        canzone.id = doc.id;

        return canzone;
      });

      Promise.all(promises).then((canzoni) => {
        cambiaCanzoni(canzoni);
      });

      return function cleanup() {
        console.log("Removed Listener");
        removeListener();
      };
    });
  }, []);

The getCanzoni function is imported from another files and it's definition is:

export function getCanzoni(utente) {
  return firestore
    .collection("Canzoni")
    .where("utente", "==", utente.uid)
    .orderBy("data", "desc");
}

When I remove the component, I don't see the 'Removed Listener' in the console. I know that the clean-up function is called when the dependency array changes or when the components is unmounted.

Any idea or tips?

I've found the error:

The clean up function must be defined in the hook's function body, not inside other function, like this:

  useEffect(() => {
    let removeListener = getCanzoni(utente).onSnapshot(function (querySnapshot) {
      let promises = querySnapshot.docs.map(async function (doc) {
        let canzone = doc.data();
        canzone.id = doc.id;

        return canzone;
      });

      Promise.all(promises).then((canzoni) => {
        cambiaCanzoni(canzoni);
      });
    });

    return function cleanup() {
      console.log("Tolto il listener");
      removeListener();
    };
  }, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM