So I'm trying to get Nuxt to query my GQL API for the site menus. I'm doing this via the nuxtServerInit
function in my index.js
store module.
Like so:
menuLocations = ["MAIN_MENU", "WORK_MENU"]
store.dispatch("menus/QUERY_MENUS", menuLocations)
Which calls my QUERY_MENUS
action from my menus.js
store module. The code for that is this:
// Define State defaults
export const state = () => ({
locations: {}
})
// Define mutations
export const mutations = {
SET_MENU(state, data) {
//Vue.set(state.locations, data.location, data.items)
//state.locations = { ...state.locations, [data.location]: data.items }
}
}
// Define actions
export const actions = {
async QUERY_MENUS({ commit }, menuLocations) {
let client = this.app.apolloProvider.defaultClient
// Get each menu from server
for (const location of menuLocations) {
const query = await client.query({
query: MenuByLocation,
variables: {
location: location
}
})
// Commit menu to store
commit("SET_MENU", {
location: _camelCase(location),
items: _get(query, "data.menuItems.nodes", {})
})
}
}
}
The problem is the both the commented out lines in SET_MENU
don't work reliably (when un-commented), sometimes they work, sometimes they don't. I'm guessing it has to do with Nuxt and SSR, or perhaps I'm doing my async/await stuff wrong?
CODE SANDBOX HERE:
Code: https://codesandbox.io/s/j3yjz2wm6y?fontsize=14
Preview: https://j3yjz2wm6y.sse.codesandbox.io/
Any suggestions? Thanks!
In provided sandbox there two errors:
1) There no await for dispatch in nuxtServerInit
export const actions = {
async nuxtServerInit(store, context) {
let menuLocations = ["MAIN_MENU", "OUR_WORK_MENU"];
await store.dispatch("menus/QUERY_MENUS", menuLocations);
}
};
2) In computed property a state reference is missed
return _get(this, "$store.state.menus.locations.mainMenu", false);
Here fixed CBS -> https://codesandbox.io/s/rrrv17oq8m