I have Vue components that are listening for Firebase events and I create the Firebase reference/listeners when they're mounted. But when a user navigates away from that page, I want to remove all the listeners in the beforeDestroy()
lifecycle hook. Is this the "correct" way of removing Firebase ref/listeners?
getFirebaseRef(path){
return firebase.database().ref(path)
},
beforeDestroy(){
// get firebase ref
let fbPath = `/projects/proj_${this.currentLessonId}/components/${this.component.id}`
this.getFirebaseRef(fbPath)
.then((ref) => {
// remove listener
ref.off("value", (snap) => {
})
ref.off("child_added", (snap) => {
})
ref.off("child_removed", (snap) => {
})
})
},
mounted(){
// get firebase ref
let fbPath = `/projects/proj_${this.currentLessonId}/components/${this.component.id}`
this.getFirebaseRef(fbPath)
.then((ref) => {
// add listener
ref.on("value", (snap) => {
doSomething1()
})
ref.on("child_added", (snap) => {
doSomething2()
})
ref.on("child_removed", (snap) => {
doSomething3()
})
})
},
Detach listeners Callbacks are removed by calling the removeEventListener() method on your Firebase database reference.
You can use Firebase's REST API to get access to the "raw" data. You can use any Firebase URL as a REST endpoint. All you need to do is append ". json" to the end of the URL and send a request from your favorite HTTPS client.
Try using: firebaseRef. off(); This will end your connection with firebase and stop communicating with the database.
A function returned by onSnapshot() that removes the listener when invoked.
You can always do call but it gets trickier if you have more than one listener on the same path.
ref.off("value")
Listeners return a reference to that listener, so this is the way I do it.
let listener = ref.on("value", function(snapshot){
//do something
}
ref.off("value", listener)
Firebase has ability to Detach listeners Callbacks are removed by calling the off() method on your Firebase database reference.
You can remove a single listener by passing it as a parameter to off(). Calling off() on the location with no arguments removes all listeners at that location.
Calling off() on a parent listener does not automatically remove listeners registered on its child nodes; off() must also be called on any child listeners to remove the callback. For read more click this link. https://firebase.google.com/docs/database/web/read-and-write
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With