Search code examples
javascriptfunctionvue.jsvue-componentvuex

Cant dispatch action without mutation


I cant dispatch an action with vuex without committing a mutation.

I imported the usual mapActions etc. like always (bare in mind all works correctly, I can execute mutations, getters, get my state all via mapMutations, mapActions etc., I can even dispatch actions IF I include a commit).

For the most simple thing I created an action in my dedicated store/actions.js.

repeatWord(data) {
console.log(data)
}

on my vue component I defined it like following:

methods: {
...mapActions({
repeatWord: 'repeatWord'
)}

and I call it via:

this.repeatWord('test')

Should work, right? Well, it doesnt. What i get in the console is {getters: {...}, state: {...}, rootGetters: {...}, dispatch: f, commit: f,...}

What am I missing here?


Solution

  • From the docs:

    Action handlers receive a context object which exposes the same set of methods/properties on the store instance

    That comes in as the first argument. The second argument is your passed data. So define your action like this:

    repeatWord(context, data) {
       console.log(data)
    }
    

    Often you'll see that context argument destructured like:

    repeatWord({ commit, dispatch }, data) {
       console.log(data)
    }