Unsubscribe Firestore listener on logout

Viewed 1073

The straightforward way to do this is explained here

However i am having a hard time trying to trigger the unsubscribe within a onAuthStateChanged which is in a different vuex module

store/user.js

...
  onAuthStateChanged({ commit, dispatch }, { authUser }) {
    if (!authUser) {
      commit('RESET_STORE')
      this.$router.push('/')
      return
    }
    commit('SET_AUTH_USER', { authUser })
    dispatch('database/getUserItems', null, { root: true })
    this.$router.push('/home')
  }
...

store/database.js

...
getUserItems({ state, commit }, payload) {
    const unsubscribe = this.$fireStore
      .collection('useritems')
      .where('owner', '==', this.state.user.authUser.uid)
      .onSnapshot(
        (querySnapshot) => {
          querySnapshot.forEach(function(doc) {
          // STUFF
        },
        (error) => {
          console.log(error)
        }
      )
  },
...

How do i reference unsubscribe() from the user.js module when the user logs out (authUser undefined)?

1 Answers

I think you can just save it in you Vuex state tree and call it from there.

  state: {
    //....
    listenerUnsubscribe: null,
    //....
  },
  mutations: {
    //....
    SET_LISTENER_UNSUBSCRIBE(state, val) {
        state.listenerUnsubscribe = val;
    },
    RESET_STORE(state) {
        state.listenerUnsubscribe()
    }
    //....
  },
  actions: {
    //....
    getUserItems({ state, commit }, payload) {
        const unsubscribe = this.$fireStore
        .collection('useritems')
        .where('owner', '==', this.state.user.authUser.uid)
        .onSnapshot((querySnapshot) => {
            querySnapshot.forEach(function(doc) {
            // STUFF
            },
            (error) => {
            console.log(error)
            }
        );
        commit('SET_LISTENER_UNSUBSCRIBE', unsubscribe);
    },
Related