firebasevue.jsgoogle-cloud-firestorenuxt.jsvuefire

Access this.$fireStore in vuex action (Nuxt.js)


Here it is stated that $fireStore could be accessed inside vuex action:

async randomVuexAction({ commit, state, rootState }, userId) {
  const ref = this.$fireStore.collection('users').doc(userId)
  ...
}

Problem: After triggering action in store/index.js:

addItem: ({ commit, getters }, itemName) => {
  const item = { name: itemName }
  this.$fireStore.collection('items').add(item).then((res) => {})
}

I'm getting error: Cannot read property '$fireStore' of undefined. Generally speaking, console.log(this) inside all actions except nuxtServerInit() - gives undefined. So is it even possible to utilize $fireStore in vuex or documentation is misleading?


Solution

  • Try removing the arrow notation for your action (because 'this' does not refer to the same thing with arrow notation) i.e.

    addItem ({ commit, getters }, itemName) {
      const item = { name: itemName }
      this.$fireStore.collection('items').add(item).then((res) => {})
    }
    

    Note: the same applies to computed properties and methods in Vue components. Follow the docs, don't change things for the sake of it.