drake035
drake035

Reputation: 2897

Can't access my store object from my component

In my store module /store/template.js I have:

const templateConfig = {
  branding: {
    button: {
      secondary: {
        background_color: '#603314',
        background_image: ''
      }
    }
  }
}

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

export const actions = {
  initializeStore (state) {
    state.branding = templateConfig.branding
  }
}

(initializeStore() is called when app initially loads)

I want to retrieve the branding the branding object in my component:

computed: {
  ...mapState({
    branding: state => state.template.branding
  })
}

But when trying to console.log() branding I see this:

enter image description here

Why don't I simply see the branding object? (and what on earth is this?)

Upvotes: 2

Views: 569

Answers (2)

Dan
Dan

Reputation: 63139

You need to always use a mutation to change state. You can call one from your action:

export const mutations = {
  SET_BRANDING(state, payload) {
    state.branding = payload;
  }
}
export const actions = {
  initializeStore ({ commit }) {
    commit('SET_BRANDING', templateConfig.branding);
  }
}

What you're seeing with the observer is normal, and indicates that the branding object has been successfully mapped and accessed.

What you see is Vue's observable object, which is how Vue implements reactivity. Without this, there would be no reactivity, and you will see such a wrapper on all top-level reactive objects. You can pretend it's not there.

Vue in fact applies this same "wrapper" to the data object internally to make it observable:

Internally, Vue uses this on the object returned by the data function.

You won't see it on other reactive properties, but if they're reactive, they belong to some parent observable object.


Upvotes: 1

kissu
kissu

Reputation: 46814

You need to import { mapState, mapActions } from 'vuex' (already done I guess).

And then, you can write this

...mapState(['branding']) // or ...mapState('@namespacedModule', ['branding'])

Still, why do you not simply put the state directly (with your background_color) rather than going through a Vuex action ?

If you want to keep it this way, do not forget to await this.initializeStore() in your component before trying to access the state.

Upvotes: 0

Related Questions