Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove/Off for Firebase Listeners

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()
    })
  })
},
like image 915
jj008 Avatar asked Aug 17 '18 20:08

jj008


People also ask

How do I get rid of Firebase listener?

Detach listeners Callbacks are removed by calling the removeEventListener() method on your Firebase database reference.

How can I read data from Firebase without listener?

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.

How do I turn off firebase realtime database?

Try using: firebaseRef. off(); This will end your connection with firebase and stop communicating with the database.

What is unsubscribe in firebase?

A function returned by onSnapshot() that removes the listener when invoked.


2 Answers

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)
like image 84
Saccarab Avatar answered Oct 18 '22 21:10

Saccarab


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

like image 34
Avinash Kant Avatar answered Oct 18 '22 19:10

Avinash Kant