[Vuejs]-Vuex state keeps saying its undefined

2👍

You can try this. You can use namespaced modules

// post.js
import axios from 'axios'

export default {
    namespaced: true,
    state: {
        testState: 'Hello',
        TV: 0,
    },
    getters: {
     getTestState: state => state.testState
    },
    mutations: {
      setTestState(state, payload) {
          state.testState = payload
      }
    },
    actions: {
      setTestState({ commit }, payload) {
         commit('setTestState', payload)
      }
    }

}
// index.js

import Vue from 'vue'
import Vuex from 'vuex'
import post from './post'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    post
  }
})
// Component

computed: {
    ...mapState('post', ['testState', 'TV']),
    ...mapGetters('post', 'getTestState') // this.getTestState
},
methods: {
   ...mapActions('post', ['setTestState']) // this.setTestState('hello from action')
}
👤Naren

1👍

Since you’re using a module try out:

...mapState({testState:state=>state.post.testState})

Your module shouldn’t create a store instance, it should be like :

export default {
    namespaced: true,
    state: {
        testState: 'Hello',
        TV: 0,
    },

    getters: {
    
    },

    mutations: {

    },

    actions: {

    }
}

Leave a comment