Vuex mapstate object undefined and "[vuex] unknown mutation type: "

Fabio Venturi Pastor picture Fabio Venturi Pastor · Mar 9, 2018 · Viewed 14k times · Source

I'm new with vue.js and vuex and I've an issue with the mapstate object, first I've only one module in my store:

-Store
 -index.js
 -mutations.js
 -actions.js
 -state.js

state.js :

export default {
    userInfo: {
        messages: [{ 1: 'test', 2: 'test' }],
        notifications: [],
        tasks: []
    }
}

So when I try to access the userInfo object everything works correctly:

computed: {
    ...mapState(["userInfo"]),
}

Then I decided to create modules:

-Store
 -modules
  -ldap.js
 -commons.js
 -index.js

So the userInfo is in the commons.js file and now when I try to get the object I always get undefined:

commons.js

// state
const state = {
    userInfo: {
        messages: [{ 1: 'test', 2: 'test' }],
        notifications: [],
        tasks: []
    }
}

export default {
    actions,
    mutations,
    state  
}

Component.vue

computed: {
    ...mapState(["userInfo"]), // <---- undefined
}

main.js :

import Vue from 'vue'
import Vuex from 'vuex'
import commons from './commons'
import ldap from './modules/ldap'

Vue.use(Vuex)

export default new Vuex.Store({
    modules : {
        commons,
        ldap
    } 
})

Can you tell me how to access the userInfo object?

Thanks.

Answer

acdcjunior picture acdcjunior · Mar 9, 2018

Considering:

  • Your commons.js is as follows:

    // state
    const state = {
        userInfo: {
            messages: [{ 1: 'test', 2: 'test' }],
            notifications: [],
            tasks: []
        }
    }
    
    export default {
        namespaced: true, // <== make sure this is defined
        actions,
        mutations,
        state  
    }
    
  • And main.js imports it like:

    import commons from './commons'
    // ..
    export default new Vuex.Store({
        modules : {
            commons,
            ldap
        } 
    })
    
  • Then update on Component.vue:

    import { mapState } from 'vuex'
    
    // ...
    
    computed: {
        ...mapState('commons', ["userInfo"]), // <== add module name here
    }
    

    Or

    import { createNamespacedHelpers } from 'vuex'
    
    const { mapState, mapActions } = createNamespacedHelpers('commons')
    
    // ...                          notice module name above ^^^^^^^^^
    
    computed: {
        ...mapState(["userInfo"]),
    }
    

"[vuex] unknown mutation type: "

Since you are now namespacing your commons module, that modules' mutations now must be prefixed.

So, say you had a mutation like:

const mutations = {
    changeName(state, data) {
        state.name = data;
    }
}
export default {
    namespaced: true, 
    actions,
    mutations,
    state  
}

And you used it like:

this.$store.commit('changeName', "New Name");

Now use it like:

this.$store.commit('commons/changeName', "New Name");