0
votes

I have an object inside the Vuex state with certain server details. The state, mutation and getter look like this:

// Code inside store/index.js of the nuxt application

const state = () => ({
  serverDetails: {}
})

const mutations = {
  SERVER_DETAILS(state, value) {
    Vue.set(state, 'serverDetails', value)
  }
}

const getters = {
  getServerDetails(state) {
    console.log('GETTER: get details')
    return state.serverDetails
  }
}

export { state, mutations, getters }

Those details are initialized in the browser via an axios Ajax call, which does commit() on completion, e.g.

commit('SERVER_DETAILS', data)

Now I try to access those details inside the browser console but get different results.
Inside the browser console:

Output in the console during initial page load:
  GETTER: get details

> $store.state.serverDetails.timezone
  Output: 7200

> $store.getters.getServerDetails.timezone
  Output: undefined

> $store.commit('SERVER_DETAILS', {timezone: 123})
> $store.state.serverDetails.timezone
  Output: 123

> $store.getters.getServerDetails.timezone
  Output: undefined

As the output GETTER: get details is only displayed once on page load it seems, that Vuex caches the getters response and does not even call thee getter function later. Not even after I manually trigger a commit()...

Question: Am I doing something wrong here? Why does the getter return an empty object, while directly accessing the state works?

2
How do you init your store? - Styx
@Styx it's a nuxt application; the above store/mutations/getters code is inside the folder 'store/index.js'. I've added the last line of the store/index.js file above - Philipp
Try state.serverDetails = { ...value } in your mutation, instead of Vue.set() call. - Styx

2 Answers

0
votes

Though, this does not solve the actual problem (getter is not updated on commit) - this workaround forces Vuex to re-initialize the entire state.

I have added this code in an axios ajax response handler, which occurs only once per session:

commit('SERVER_DETAILS', data)

$store.hotUpdate($store.state) // <<-- This line is new.
0
votes

You are using the Vuex state wrong, it should be an object.

const state = {
  serverDetails: {},
}