0
votes

I'm trying to stop listening to Firestore onSnapshot from other function.

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

How can i fix this?


  let unsucscribe;


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


  function unsubscribeFirestore() {
    unsubscribe(); // throws an error that unsubscribe is not a function.
  }

  
  unsubscribeFirestore();
1

1 Answers

0
votes

You're useEffect won't complete until after the first render in React, so check that unsubscribe is not undefined before trying to call it.


  let unsubscribe;


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


  function unsubscribeFirestore() {
    if (unsubscribe !== undefined) {
      unsbscribe(); // throws an error that unsubscribe is not a function.
    }
  }

  
  unsubscribeFirestore();