javascriptfirebasefirebase-realtime-databasevue.js

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()
    })
  })
},

Solution

  • 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)