lokanath
lokanath

Reputation: 247

in Vuex, How to load state and use data from the state when the application loads/renders first ?, I am using nuxt, Vue and Vuex as store

I am trying to load data from a JSON file into the VueX store, but the state does not get loaded until I try to refresh the VueX Store manually.

what I am trying to achieve is, before the app renders, the state should be loaded with the data. Like before I access the homepage.

But I see on the Vue Devtools, that if set it to recording mode, then the app loads the data.

Below is code from store/index.js

//store/index.js
const exec = (method, { rootState, dispatch }, app) => {
  const dispatches = [];
  Object.keys(rootState).forEach(async (s) => {
    dispatches.push(await dispatch(`${s}/${method}`, app));
  });
  return dispatches;
};

export const actions = {
  nuxtServerInit(store, ctx) {
    console.log('nuxtServerInit');
    exec('init', store, ctx);
  },
  nuxtClientInit(store, ctx) {
    console.log('nuxtClientInit');
    exec('init', store, ctx);
  },
  init(store, ctx) {
    console.log('nuxtInit');
    exec('init', store, ctx);
  },
};

store/app.js

//store/app.js
export const state = () => ({
  config: {},
});

export const mutations = {
  SET_CONFIG(state, config) {
    state.config = config;
    }
  }
};

export const getters = {
  config: (state) => state.config,
};

const loadConfig = ({ commit  }) => {
  const siteConfig = require('../config/data.json');
  const appConfig = JSON.parse(JSON.stringify(siteConfig.properties));
  commit('SET_CONFIG', appConfig);
};

export const actions = {
  init(store, ctx) {
    loadConfig(store);
  },
};

Here the state is empty when the app loads. How can I access that when the app loads? 



Upvotes: 0

Views: 1146

Answers (1)

thopaw
thopaw

Reputation: 4044

I normally call the init action of my store in the layout.

When this is too late you could also do it in a plugin, I guess. You can use the context.store in the plugin.

// plugins/init.js
export default ({ store }) => {
    store.dispatch("init")
}
// store/index.js
export actions = {
  init(context) {
    // ...
  }
}

Upvotes: 1

Related Questions