[Vuejs]-Getting error "TypeError: this.$state is undefined" using Vuex on VueJS project

1👍

You should already have something like this to initialize vue and vuex

import Vue from 'vue'
import App from './App' // src/App.vue
import store from './store' // store/index.js

Vue.use(store)

new Vue({ store, render: h => h(App) }).$mount('#app') // notice the "store" attribute here

So in component, it should be available in this.$store.state

And also, as @skirtle has pointed out, use computed if you want it to reactive with vuex

computed: {
  isLoggedIn () {
     return  this.$store.getters.user != null // remove .state
     // or you can use the state directly
     // return  this.$store.state.user != null
  }
}

In vuex, you should make change to state with a mutation. I see you already have setUser

setUser(state, payload) {
  state.user = payload // change this.user to state.user
},

you can then change the state in component with this.$store.commit('setUser', this.user)

And I see you have made an action setUserAction to do 3 commits, so you can just call it in component with this.$store.dispatch('setUserAction', this.user)

Leave a comment