I'm building mobile chat application with firebase real-time database and react native. This application is always listening to fetch new chat messages from firebase database.
But I see the following error message when I click sign out
button on chat screen because the application in the background always tries to fetch new messages even I have signed out and I don't have a role to read and write chat messages.
This is the error message.
console.error: "Uncaught Error in onSnapshot:", {"code": "permission-denied", "name": "FirebaseError" }
This is my code for listening to fetch the new chat messages.
:
this.firebase.firestore.collection("chat").doc(" chatId").collection("messages")
.where('counter', '>', this_.messageCounter - Const.chatPagingMessageCount).orderBy('counter', 'asc')
.onSnapshot(function (querySnapshot) {
:
I would like to make users sign out without that error.
You should remove listener when user left from chat. You can use componentWillUnmount lifecycle method or sign out action for that.
https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener
componentDidMount () {
this._listenToMessages();
}
componentWillUnmount () {
this.chatListener();
}
_listenToMessages = () => {
this.chatListener =
this.firebase.firestore.collection("chat").doc("chatId").collection("messages")
.where('counter', '>', this_.messageCounter -
Const.chatPagingMessageCount).orderBy('counter', 'asc')
.onSnapshot(function (querySnapshot) {
...
}
}