0
votes

I've developed my app with react native and used Cloud Firestore for database.
I'd like to detach snapshot listener before users sign out.
How to execute unSubscribe(); in the not getDataComponent but signOutComponent?

my code is here:

// getDataComponent.js
class DataComponent extends React.Component {
  getData(year) {
    const { currentUser } = firebase.auth();
    const db = firebase.firestore();
    const docRef = db.collection(`users/${currentUser.uid}/statics`).doc(`${year}`);
    const unSubscribe = docRef.onSnapshot((doc) => {
      // ...
    }, (err) => {
      // ...
    });
  }
  render() {
    return (
      // ...
    );
  }
}
// signOutComponent.js
class signOut extends React.Component {
  signOut() {

    // I'd like to detach snapshot listner here.

    firebase.auth().signOut()
      .then(() => {
        console.log('signOut success');
      })
      .catch((error) => {
        // ...
      });
  }
  render() {
    return (
      // ...
    );
  }
}

my environment:

"expo": "^34.0.0",
"react": "16.8.3",
"react-native": "https://github.com/expo/react-native/archive/sdk-34.0.2.tar.gz",
"firebase": "^7.14.1",
1

1 Answers

1
votes

onSnapshot function returns the unsubscribe function. you can do

this.unsubscribe = ref.onSnapshot(...)

and in your componentWillUnmount method add

if(this.unsubscribe) {
this.unsubscribe();
}