Dran Dev
Dran Dev

Reputation: 519

Vuex state keeps saying its undefined

Here is my post.js under src > store > post.js:

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

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        testState: 'Hello',
        TV: 0,
    },

    getters: {
    
    },

    mutations: {

    },

    actions: {

    }
})

My 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
  }
})

And finally I tried accessing the state in a component.vue:

<template>
  <div id="app">
    <h3>{{ testState }} {{ TV }}</h3>
  </div>
</template>

<script>
import store from './store'
import { mapActions, mapState, mapGetters } from 'vuex'

export default {
  name: 'App',
  data(){
    return {
  
    }
  },
  computed: {
    ...mapState(['testState'])
  }
}
</script>

However, it keeps giving me an error on the console that says:

Property or method "testState" is not defined on the instance but referenced during render.

When I check in the Vue panel (Chrome's devtools) and I check under Vuex, I can clearly see the testState: 'hello' there so the state exists.

Any tips/advices? Thanks a lot!

Upvotes: 0

Views: 556

Answers (2)

Naren
Naren

Reputation: 4480

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')
}

Upvotes: 2

Boussadjra Brahim
Boussadjra Brahim

Reputation: 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: {

    }
}

Upvotes: 1

Related Questions