Home » vue » Getting undefined when trying to read vuex state

Getting undefined when trying to read vuex state

Posted by: admin November 26, 2021 Leave a comment

Questions:

Following a simple example in VueMaster course and can’t seem to read state from the store. Here’s my main.js:

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
import App from './App.vue'
import router from './router'
import store from './store'

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

And here’s my index.js in the /store folder:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: { id: 'abc123', name: 'Adam Jahr' },
  },
  mutations: {},
  actions: {},
  modules: {}
})

Then, I try and read the state object from a component:

<template>
  <div>
    <h1>Create an Event, {{ $store.state.user.name }}</h1>
  </div>
</template>

I don’t see anything in the browser for the component. Console shows an error "TypeError: Cannot read property ‘name’ of undefined".

Any idea why this very simple example doesn’t work? Thanks.

Answers:

Shouldn’t your import look like this:

import store from './store/index'

since that is where you are creating your store, check the folder structure, maybe that is the problem.

###

I didn’t see any problem with your code, it’s working as expected.

Here is sandbox link – https://codesandbox.io/s/silly-poitras-sosvs?file=/src/App.vue

###

You need to provide the store in your component
Something in computed like
return this.$store.state.user