Search code examples
vuexstorenuxt.js

vuex unknown action (or mutation) type


I'm writing a simple code to set token in store in an Nuxt application. when I tried to call a mutation or action from my store, this error is logged in console: [vuex] unknown action type: setToken

import Vuex from 'vuex';

export const store = new Vuex.Store({
    state:()=> ({
        token: ''
    }),
    getters: {
        getToken: state => {
            return state.token;
        }
    },
    mutations: {
        setToken: (tokenStr) => {
            state.token = tokenStr;
        }
    },
    actions: {
        setToken: ({ commit }, tokenStr) => {
            commit('setToken', tokenStr);
        }
    }
})

This is a method trying to call the mutation:

methods:{
  setToken(){
    this.$store.dispatch('setToken','token1');
    this.token = this.$store.getters.token;
  }
}

Solution

  • You are using the 'classic' and now deprecated method of setting the vuex store in nuxt. You should set it up like this:

    // store/index.js
    export const state = () => ({
      token: ''
    })
    
    export const mutations = {
      SET_TOKEN (state, tokenStr) {
        state.token = tokenStr
    }
    
    export const actions = {
      setToken ({ commit }, tokenStr) {
        commit('SET_TOKEN', tokenStr)
      }
    }
    
    export const getters = {
      token: (state) => state.token
    }
    

    Nuxt will build the store for you from there. You can see it in the doc here.