I have a situation where I get data from api in nuxtServerInit and write it to the store's state variable like so
let categoriesService = new Categories(this.$axios);
categoriesService.current().then((resp) => {
if (resp.data.success) {
const navCategoryRoutes = resp.data.items
.filter((item) => {
return item.label !== "" && item.label;
})
.map((item) => {
item.label = item.label.toLowerCase();
item.isSelected = false;
item.url = "/category/" + item.name + "/";
return item;
});
commit("nav/setNavCategoryRoutes", navCategoryRoutes);
}
});
I log it in the setter to the console and I can see that below the assignment declaration and I can see it's there
state: {
categoryRoutes: [
[Object],
[Object],
[Object],
[Object],
[Object]
]
},
In the getter, however, it's always an empty array ;/
export const getters = {
getNavCategoryRoutes(state) {
console.log({ getter: state });
return state.categoryRoutes;
},
};
getter: {
categoryRoutes: []
}
and in the file where I try to use it obviously it is empty as well
categories() {
console.log({
header: this.$store.getters["nav/getNavCategoryRoutes"],
});
return this.$store.getters["nav/getNavCategoryRoutes"];
},
I have tried to fetch it in computed property:
computed: {
categories() {
return this.$store.getters["nav/getNavCategorysRoutes"];
},
},
and in the mounted lifecycle method:
mounted() {
this.categories = this.$store.getters["nav/getNavCategoryRoutes"];
},
But the problem is earlier in the getter I think, I just don't know what am I doing wrong ;/ this getter is no different from the working ones. Would you please point me in the proper direction, I am out of ideas about what to do with that, thanks a lot.
To get data in nuxtServerInit, add nuxtServerInit to actions:
nuxtServerInit({ commit }) {
// get data then commit mutation
})