简体   繁体   中英

react + firebase unsubscribe is not a function in useEffect

I would like to understand why the following code would trigger this error?

TypeError unsubscribe is not a function

It doesn't have such error when i used .onSnapshot() function instead of get() .

Thanks

  useEffect(() => {
    const unsubscribe = database
      .collection("Maps")
      .doc(id)
      .collection("Entries")
      .get()
      .then(
        data => {
          data.forEach(doc => {
            console.log(doc.id, " => ", doc.data());
          });
          setLoading(false);
        },
        err => {
          setError(err);
          console.log(err);
        }
      );
    return () => unsubscribe();
  }, [id]);

You can't unsubscribe from a get() call. Because of that, the get() doesn't return an unsubscribe method, and your call fails.


When you start listening for data with onSnapshot , the client keeps listening for changes to the data. For that reason it returns a function that you can call to stop listening.

When you call get() to load data, the client gets the data from the server once, and then immediately stops listening for changes. That's why there's no need to unsubscribe (nor the possibility to stop) after you call get() .


If there's a chance that the loading of the data may take longer than the component is mounted, you'll want to check for the unmounting of the component inside the then() handler. For an example of this, see Is there a way to check if the react component is unmounted?

Unsubscribe() isn't a function because what is returned from database is not a function. Call a function in return for cleanup. Have a function that does the clean up and call it.

unsubscribe worked for real-time listener (onSnapshot). Get() is used in asynchronous function and return a promise.

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