How should I call NuxtServerInit correctly?

Viewed 2091

There is such code in the VUEX repository:

export const state = () => ({
  z: 'sdfjkhskldjfhjskjdhfksjdhf',
});

export const mutations = {

  init_data_for_firmenistorie2 (state, uploadDbFirmenistorieData){
    state.z = uploadDbFirmenistorieData;
  },


};

  async nuxtServerInit ({commit}) {
    console.log('111');
    commit('init_data_for_firmenistorie2', 123)
  }


}

My question is:
How should I call to nuxtServerInit in such a way that I can use it to rewrite the value of state z?
P.S. Right now my code is not working.

2 Answers

If your store/index.js has an action nuxtServerInit, then Nuxt will invoke it.

So your code ends up looking like

export const state = () => ({
  z: 'sdfjkhskldjfhjskjdhfksjdhf',
});

export const mutations = {
  init_data_for_firmenistorie2(state, uploadDbFirmenistorieData) {
    state.z = uploadDbFirmenistorieData;
  },
};

export const actions = {
  nuxtServerInit({ commit }) {
    console.log('111');
    commit('init_data_for_firmenistorie2', 123);
  },
};

Well you create a actions object, and then you put your nuxtServerInit in there:

export const actions = {
   nuxtServerInit(vuexContext, context){
      vuexContext.commit('init_data_for_firmenistorie2', 123);
   }
}

With context you can additional have access to for example params, routes, redirect etc. The docs: https://nuxtjs.org/api/context

Related