0
votes

I'm trying to use useEffect to stop listening to Firebase Firestore collection changes.

I can get Firebase data, But I can't access this unsubscribe();

How can i fix this?


  let unsbscribe;

  async function getFirebaseData() {
      unsbscribe = db.collection('room')
          .where('joinUser', 'array-contains-any', [10])
          .onSnapshot((res) => {
            // do something...
          });


  useEffect(() => {
    getFirebaseData();
    return () => {
      unsbscribe(); // throws an error that unsubscribe is not a function.
    };
  }, []);

2

2 Answers

0
votes

Try to return just unsubscribe

 let unsbscribe;

  async function getFirebaseData() {
      unsbscribe = db.collection('room')
          .where('joinUser', 'array-contains-any', [10])
          .onSnapshot((res) => {
            // do something...
          });


  useEffect(() => {
    getFirebaseData();
    return unsubscribe
  }, []);
0
votes

You can unsubscribe it from inside the useEffect hook in this way:

useEffect(() => {
    const unsubscribe = db.collection('room')
        .where('joinUser', 'array-contains-any', [10])
        .onSnapshot((res) => {
            // do something...
        });
    return () => unsubscribe()
}, []);