Where to initialize Vuex store at app start up?
-
When my app starts, I need to populate my Vuex store from my backend serve with some configuration data. What is the “best practice” for doing this? I will be calling a Vuex action to get the data from the server.
Should I do it in a boot file located in the boot folder? In the store/index.js file? Use a life cycle hook(created) in the App.vue file? Some other recommend method?
Thanks.
-
@rhscjohn preferably in a boot file.
-
I went with adding a boot file. I also had to make changes to the Vuex store directory to make the store available to the boot file.
I made changes to the vuex index.js file located in the store folder.
src\store\index.js
import Vue from "vue"; import Vuex from "vuex"; import devices from "./devices"; import channels from "./channels"; import settings from "./settings"; import recordings from "./recordings"; import video from "./video"; import guide from "./guide" import schedule from "./schedule" Vue.use(Vuex); /* * If not building with SSR mode, you can * directly export the Store instantiation */ let store = null //added export default function ({ store/*store, ssrContext */ }) { //modified const Store = new Vuex.Store({ modules: { devices, channels, settings, recordings, video, guide, schedule }, // enable strict mode (adds overhead!) // for dev mode only strict: process.env.DEV }); store = Store // added return Store; }
Then in the boot directory I added a file called init.js.
src\boot\init.js
// import something here // "async" is optional; export default async ({ app, router, Vue, store }) => { console.info('boot: init entered', store) await store.dispatch('settings/getNPVRConfig') console.info('boot: init exited') }
-
@metalsadman @rhscjohn i have seen this solution before.
https://forum.quasar-framework.org/topic/4685/trouble-accessing-data-from-boot-file/5
but I don’t understand why the default export in store index.js would not work in boot and .js files ( because vuex exports a function instead of a variable?). Could you explain?
why is this necessary:
let store = null //added ... store = Store // added
for example this works in my boot file( vuex-router-sync setup):
import { sync } from 'vuex-router-sync' export default async ({ app, router, store }) => { const unsync = sync(store, router) // done. Returns an unsync callback fn }
without the extra code in store/index.js:
-
@dobbel yes because it’s a function, in the boot is different, the store instance is passed as a parameter it’s the same store instance in your
src/store/index.js
, you’ll get more context if you check.quasar/client-entry.js
file (if I’m not wrong), to see how those are initialized, you’ll also see there why $router instance is accessible in your stores via this.$router (if you are usingfunction
instead of arrows). I suggest you check that folder out in your project.