Отписаться от слушателя Firestore при выходе - PullRequest
0 голосов
/ 24 марта 2020

Простой способ сделать это объяснен здесь

Однако я испытываю трудности с попыткой вызвать отписку в onAuthStateChanged, который находится в другом модуле vuex

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

Как ссылаться на unsubscribe() от пользователя. js модуль, когда пользователь выходит из системы (authUser undefined)?

1 Ответ

0 голосов
/ 24 марта 2020

Я думаю, вы можете просто сохранить его в своем дереве Vuex state и вызвать его оттуда.

  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);
    },
...