0
votes

I have a namespaced Vuex store module, and I am trying to access that module's state in a component (via mapState) to set a default value in my data. However, the "mapped state" is always undefined in my component.

My store is:

cartDetail.js

export const defaults = {
  id: null,
  items: [],
},
const state = { ...defaults, };
export default {
  namespaced: true,
  state,
}

and in my component, I have:

<script>
 import { mapState, mapActions, } from 'vuex';

 data() {
    defaultSelected: this.cartDetail.items[0],
 },

 computed () {
  ...mapState('cartDetail', ['cartDetail,'],),

  setDefaultSelected () {
   return this.cartDetail.items[0];
  },
 },

 created () {
    this.cartFetch(userId);
 }
</script>

Even when I console.log(this.cartDetail); in either my setDefaultSelected computed, or in created hook, it is undefined! Any help would be much appreciated!!

1

1 Answers

0
votes
  1. your data section looks incorrect. It should look like this:
data() {
    return {
      defaultSelected: this.items[0]
    }
 },

  1. In mapState you should indicate state props (and their module name if they are not from the root state). I assume that carDetail.js is a store module.
computed () {
  ...mapState({
     id: state => state.cartDetail.id,
     items: state => state.cartDetail.items
  }),

  setDefaultSelected () {
   return this.items[0];
  },
 },