Leonardo Ebert
Leonardo Ebert

Reputation: 139

Nuxt.js Vuex module not working as expected

I'm having problems with Nuxt's Vuex using it in modules.

It turns out that the state is being declared and appears in Vuex, the actions are triggered, but the mutation changes the state instance, but do not commit the change and do not even trigger the event, as it does not appear in the Vuex devtools console, below Vuex module code.

Note: in both console.log() print the state, in the first, empty, as it was declared, and in the second, the changed state, but the change does not really reflect in Vuex.

export const strict = false
export const state = () => ({
  address: {}
})

export const mutations = {
  setShopAddress(state, address) {
    console.log(state)
    state.address = address
    console.log(state)
  }
}

export const actions = {
  getAddress({
    commit
  }) {
    this.$axios
      .get('/general/address')
      .then((response) => {
        commit('setShopAddress', response.data)
      })
      .catch((e) => console.error(e))
  },
  setAddress(vuexContext, address) {
    vuexContext.commit('setShopAddress', address)
  }
}

export const getters = {
  getShopAddress(state) {
    return state.address
  }
}

Upvotes: 1

Views: 710

Answers (1)

Leonardo Ebert
Leonardo Ebert

Reputation: 139

After many hours and thanks to a group of Nuxt on Telegram I was able to find the solution, I just needed to put an async on nuxtServerInit and an await on the call to action.

Code below:

async nuxtServerInit({ dispatch }) {
    await dispatch('module/action')
},

I hope my answer helps more people

Upvotes: 1

Related Questions