Search code examples
vue.jsfirebase-realtime-databasevuejs2vuex

Call Vuex Action via Vue Computed Setter


I have a value for a counter stored in Firebase.

{
  name: 'sheep',
  total: 0
}

I sync that to a value in Vuex state using an action calling Firebase.

loadedCounter ({ commit }) {
  commit('setLoading', true)
  firebase.database().ref('animals').on('value', (snapshot) => {
    let counter = []
    let obj = snapshot.val()
    for (let key in obj) {
      counter.push({
        name: obj[key].name,
        total: obj[key].total
      })
    }
    commit('setLoadedCounter', test)
    commit('setLoading', false)
  })
},

I then use a computed property in my Vue component to get the value. The getter is working.

computed: {
sheepCounter: {
  get () {
    let test = this.$store.getters.getSheep
    return test.total
  },
  set (value) {
    this.$store.commit('updateSheep', value)
  }
}

The setter however errors out. I get this error in the console:

[vuex] unknown mutation type: updateSheep

I believe the issue is that the set can only reference a mutation and updateSheep is an action. But from my understanding it has to be an action because it's asynchronous code.

updateSheep ({commit}, payload) {
  firebase.database().ref('animals').child('sheep').update({total: payload})
},

How can I set the data using the computer property set that sync to firebase?


Solution

  • I was able to fix this by dispatching the action. I was trying to commit an action. Dispatching is for Actions:

    this.$store.dispatch('updateSheep', value)
    

    not

    this.$store.commit('updateSheep', value)