Ad

Framework 7 Vue How To Stop Firebase From Listening To Changes When On Different Pages?

Suppose I have pageA where I listen for a firebase document changes

export default {
  mounted() {
    this.$f7ready(() => {
      this.userChanges();
    })
  },
  methods: {
    userChanges() {
      Firebase.database().ref('users/1').on('value', (resp) => {
        console.log('use data has changed');
      });
    }
  }
}

Then I go to pageB using this..$f7.views.current.router.navigate('/pageB/')

If on pageB I make changes to the /users/1 firebase route I see this ,message in the console: use data has changed, even though I'm on a different page.

Any way to avoid this behavior, maybe unload the page somehow?

I tried to stop the listener before navigating away from pageA using Firebase.off() but that seems to break a few other things.

Ad

Answer

Are you properly removing the listener for that specific database reference? You'll have to save the referenced path on a dedicated variable to do so:

let userRef
export default {
    mounted() {
        this.$f7ready(() => {
            this.userChanges();
        })
    },
    methods: {
        userChanges() {
            userRef = Firebase.database().ref('users/1')
            userRef.on('value', (resp) => {
                console.log('use data has changed');
            });
        },
        detachListener() {
            userRef.off('value')
        }
    }
}

That way you only detach the listener for that specific reference. Calling it on the parent, would remove all listeners as the documentation specifies:

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.

More on that topic here: https://firebase.google.com/docs/database/web/read-and-write#detach_listeners

Ad
source: stackoverflow.com
Ad