Reputation: 498
I have this code which listen to changes in the Realtime database when new child added.
mUserRef = firebase.database().ref("Messages").child(conversation);
mUserRef.on("child_added", snapshot => {
const message = {
key: snapshot.key,
...snapshot.val()
};
this.onReceive(message);
});
and this code will be triggered when received new child added to the database ref
let cy = this;
firebase
.database()
.ref("LastMessages")
.child(key)
.once("value")
.then(function(snapshot) {
//...some code
});
the problem is i can't unsubscribe off the realtime listener when i use componentWillUnmount
Code for unsubscribe
constructor(props) {
super(props);
this.state = {
ready: false,
messages: []
};
}
_isMounted = false;
componentDidMount = async () => {
this._isMounted = true;
}
async retriveMessages(conversation) {
let cy = this;
cy.setState({
ready: true
});
let mUserRef = null;
if (this._isMounted) {
mUserRef = firebase
.database()
.ref("Messages")
.child(conversation);
mUserRef.on("child_added", snapshot => {
const message = {
key: snapshot.key,
...snapshot.val()
};
this.onReceive(message);
});
} else {
mUserRef.child(conversation).off("child_added");
}
}
componentWillUnmount() {
this._isMounted = false;
}
Solutions i tried:
Unsubscribing from Firebase Realtime Database
componentwillunmount to unsubscribe from firestore
how to remove firebase database listener...
How to stop Firebase Listener when i pass to another screen?
Upvotes: 1
Views: 552
Reputation: 80914
componentWillUnmount()
is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().
Therefore do the following:
componentWillUnmount() {
mUserRef.off("child_added");
this._isMounted = false;
}
Upvotes: 3