Search code examples
vue.jsvue-componentnuxt.jsvuexvuex-modules

Can't access property of Vuex store object


I initialize my store with a JSON file entitled config.json:

{
  "branding": {
    "button": {
      "secondary": {
        "background_color": "#EC6B24",
        ...
      },
      ...
    }
  }
}

... which I import in my store:

import templateConfig from '@/config.json'

export const state = () => ({
  branding: {}
})

export const mutations = {
  setConfig (state, data) {
    state.branding = templateConfig.branding
  }
}

export const actions = {
  initializeStore ({ state, commit }, data) {
    commit('setConfig', data)
  }
}

Now in my view's mounted hook, I call my store action (this.initializeStore()) so that the store gets populated on page load.

Problem is, when in one of my view's child components I try to access a nested property like so:

computed: {
  ...mapState({
    bgColor: state => state.template.branding.button.secondary.background_color
  })
}

... I'm getting this error:

Cannot read property 'secondary' of undefined

Why?

EDIT: below is the parent view component's code.

import { mapActions } from 'vuex'

export default {
  mounted () {
    this.initializeStore()
  },
  methods: {
    ...mapActions({
      initializeStore: 'initializeStore'
    })
  }
}

Solution

  • The error means the state only has its initial value at that time, and the action wasn't called yet (the parent is mounting after the child maps the state). You could try the action in the parent's created hook instead.

    However, if initializeStore is only called once at initialization, you can remove that action (and mutation) altogether, and just define your state from the imported json directly:

    import templateConfig from '@/config.json'
    
    export const state = () => ({
      branding: templateConfig.branding
    })
    

    The action / mutation never use the payload anyway.

    If data was being fetched rather than imported, I would suggest to look into nuxtServerInit and/or fetch / asyncData hooks.