Jake
Jake

Reputation: 31

Vuex map state undefined state

I'm trying to use my state here to pass through as a search query but when pulling the state down using map state it's returning 'undefined' ... I've never had this problem before.

Here's the code:

import Vue from 'vue'
import Hero from '../components/Hero/Hero'
import PopularDest from '../components/PopularDest/PopularDest'

import { mapActions, mapState } from 'vuex'

export default Vue.extend({
template: `
    <div class="page--sport">
        <hero :action="getSportData" page="sport" title="Sport Events"></hero>
        <div class="page--sport__bottom">
            <h2>Popular Sport Events</h2>
            <popular-dest></popular-dest>
        </div>
    </div>
`,
data () {
    return {
        searchQuery: {
            query: [(this as any).searchInput],
            genre: 'sport'
        }
    }
},
updated () {
   console.log(this.searchInput)
},  
components: {
    Hero,
    PopularDest
},
methods: {
    getSportData (): void {
        [(this as any ).getEventData(this.searchQuery)]
    },
    ...mapActions([
        'getEventData'
    ])
},
computed: {
    ...mapState([
        'searchInput'
    ])
}
})

I'm using Vuex modules for the first time in this project which seems to be the only indicator to a problem for me.

Upvotes: 2

Views: 6789

Answers (1)

Vishnu Nair
Vishnu Nair

Reputation: 2433

If you are using Module based Store structure apparently you cannot directly access state of a module inside mapState like that. For example, if you do - this.$store.state.searchInput you will get undefined but if you do this.$store.state.yourModuleName.searchInput you will get the actual value inside the state of that particular module.

You have two ways to fix this:

1.Property based access within mapState

...mapState({
    searchInput: state => state.yourModuleName.searchInput,
  })

2.Using Namespaces in your Module

..........
modules: {
yourModuleName: {
  namespaced: true,
.........

/* Using the namespace in mapState */
...mapState('yourModuleName',[
  'searchInput',
])

There's an open issue on this case in Vuex's github page - https://github.com/vuejs/vuex/issues/459

Upvotes: 12

Related Questions