adamb
adamb

Reputation: 427

Nuxt Vuex Store - issues with modular approach

I built a site in Nuxt and pulled in a set of menu items to the Vuex store via the WordPress API. I'm currently doing this the classic mode which is soon to be deprecated, so I want to update this to the 'modules' mode as referred to here: https://nuxtjs.org/guide/vuex-store/. I have the following code in store/index.js:

export const state = () => ({
    menuMain: null
});

export const mutations = {
    mutateMainMenu(state, data)
    {
        state.menuMain = data
    }
};

import axios from "axios/index";

export const actions = {
    async nuxtServerInit ({ commit }) {
        const response = await axios.get('http://myapi.com/wp-json/wp/v2/pages')
        commit('mutateMainMenu', response.data)
    }
};

I hoped this would be a case of moving the code below in to 'store/menuMain.js':

import axios from "axios/index";

export const actions = {
    async nuxtServerInit ({ commit }) {
    const response = await axios.get('http://myapi.com/wp-json/wp/v2/pages')
        commit('mutateMainMenu', response.data)
    }
};

However this doesn't seem to work. Does anyone have any ideas? I haven't seen the 'actions' object set in a file other than 'store/index.js' in any examples, so I'm wondering if this is the issue.

The version of Vue used in the site is 2.6.10.

Upvotes: 0

Views: 1155

Answers (2)

adamb
adamb

Reputation: 427

For anyone who struggles with this, thanks to the answer given by @EvilArthas this works with the following in the 'store/menuMain.js' file:

export const state = () => ({
    items: null
});

export const mutations = {
    mutateMainMenu(state, data)
    {
        state.items = data
    }
};

Then the following in the 'store/index.js' file:

import axios from "axios/index";

export const actions = {
    async nuxtServerInit ({ commit }) {
        return axios.get('http://myapi.com/wp-json/wp/v2/pages')
        .then(response =>
        {
            commit('menuMain/mutateMainMenu', response.data);
        })
    }
};

Upvotes: 1

Andrew Vasylchuk
Andrew Vasylchuk

Reputation: 4779

nuxtServerInitAction can only be defined in the primary module.

If you are using the Modules mode of the Vuex store, only the primary module (in store/index.js) will receive this action. You'll need to chain your module actions from there.

https://nuxtjs.org/guide/vuex-store#the-nuxtserverinit-action

Upvotes: 1

Related Questions