NuxtServerInit is not working on initial page render on nuxt js vuex module mode. But it works on Classic mode. Following code is the flow I used.
My api call
api/CategoryApi.js
import axios from 'axios';
const HEADERS = {
Accept: 'application/json'
};
export default {
getCategory(payload) {
return axios.get(`${process.env.apiUrl}/category`, {
payload,
headers: HEADERS
});
}
}
store/modules/CategoryStore.js
import api from '~/api/CategoryApi'
const state = () => ({
categories: []
});
const getters = {
allCategories: state => state.categories
};
const actions = {
async nuxtServerInit({commit}) {
const payload = {
per_page: 6,
page: 1
};
const response = await api.getCategory(payload);
commit('setCategories', response.data.data);
},
};
const mutations = {
setCategories: (state, data) => {
state.categories = data;
}
};
export default {
state,
getters,
actions,
mutations
}
pages/index.vue
<template>
<div>
<v-flex xs6 sm4 md2 class="text-xs-center my-2 pa-2" v-for="category in allCategories" :key="category.id">
{{ category.name }}
</v-flex>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
layout: 'default',
computed: {
...mapGetters({
allCategories: 'modules/CategoryStore/allCategories',
})
},
}
</script>
Am I doing this wrong? :/ I want to know the right way to implement this.
Edit: How I did with Aldarund answer (This might help someone)
Edited store/modules/CategoryStore.js
const actions = {
async fetchCategories({commit}) {
const payload = {
per_page: 6,
page: 1
};
const response = await api.getCategory(payload);
commit('setCategories', response.data.data);
},
};
Added store/index.js
const actions = {
async nuxtServerInit({dispatch}) {
await dispatch('modules/CategoryStore/fetchCategories');
},
};
export default {
actions
}