0

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]);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
innek
  • 114
  • 2
  • 13

3 Answers3

6

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?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thanks. whats the proper way of using get() in useEffect, and unsubscribe/clean it up when unmount? if i dont do `return () => unsubscribe();` console error shows cannot update state on a unmounted component, and might have memory leak – innek Apr 25 '20 at 21:52
  • perfect. thanks! and `You can accept an answer in 6 minutes`. let me wait abit – innek Apr 25 '20 at 21:55
0

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.

tksilicon
  • 3,276
  • 3
  • 24
  • 36
0

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