Search code examples
vue.jsvuexvuex-modules

Vuex - Module state returns undefined


am a little confused as to why the state property would return undefined. am new to vue.js and really need to understand how this works.

Here is what i've done

in the state.js file for let say todo module, i have

const state = () => {
    return {
        todos: [
            {
                id: 1,
                title: 'Go outside'
            },
            {
                id: 2,
                title: 'Come back in'
            }
        ]
    }
}
export default {
    state
}

i have an index file where i join everything together and export it

import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'

export default {
    state,
    getters,
    actions,
    mutations
}

and in the store entry point i have

import Todos from './modules/todos'
export default 
  modules: {
    Todos
  }
})

So, the problem is, actions works perfectly but the state is affecting other like getters and mutations since the state properties was undefined.

vue-devtool stop working in my browser so i tried to console.log(this.$store.state.todos) but yeah, it undefined


Solution

  • you have to modify the state.js file. you should export like below

    export default {
        state: {
            todos: [
                {
                    id: 1,
                    title: 'Go outside'
                },
                {
                    id: 2,
                    title: 'Come back in'
                }
            ]
        }
    }