xagos
xagos

Reputation: 98

Vuex: How to properly call action?

I'm having trouble understanding how to pass actions with payloads using Vuex. I know i need a mutation to change the state, and that its best practice to use an action to dispatch the mutation. Not sure how I call the action and pass in a parameter though. Whenever I try this I get the error:

"Uncaught TypeError: Cannot read property 'isComplete' of undefined"

// Store.js
const mutations = {
  completeTodo: function (state, todo) {
    console.log(todo)
    todo.isComplete = todo.isComplete || false
    state.toggleAll = false
  }
}

const actions = {
  completeTodo: ({commit}) => commit('completeTodo')
}

//Todo.vue

 methods: {
  ...mapActions([
    'completeTodo'
  ])
}
 <input type="checkbox" name="isCompleted" " v-on:change="completeTodo(todo)" class="todoCheck" />

Upvotes: 3

Views: 2643

Answers (1)

Austio
Austio

Reputation: 6085

Your action should take a second argument which is the payload that you are passing in your component.

const actions = {
  completeTodo: ({commit}, todo) => commit('completeTodo', todo)
}

More details

Think of like this.

Component => Knows about the todo and a completeTodo function (which is the action provided by vuex mapActions). It doesn't have to know about the store or any functions in order to get its job done.

mapActions => generates a 'smart' completeTodo function that takes care of the specific function in the store to call and the order of the arguments to correctly call it.

Upvotes: 2

Related Questions