I have a project using nuxt universe SSR. I fetch data on layout using fetch method thet trigger store action dispatch. But it doesn't work at all...
Here's the code. This is default layout file:
import Navbar from '~/components/Navbar'
export default {
components: {
Navbar
},
async fetch ({ store }) {
await store.dispatch('fetchItems')
}
}
And here's vuex store:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = () => new Vuex.Store({
state: {
allItems: [],
currentCategories: []
},
mutations: {
setItems (state, allItems) {
state.allItems = allItems
},
setCurrentCategories (state, currentCategories) {
state.currentCategories = currentCategories
}
},
actions: {
async fetchItems ({ commit, dispatch }) {
try {
const { data: { items } } = await this.$axios.get('/api/catalog/categories?limit=0')
commit('setItems', items)
dispatch('getCurrentCategories')
} catch (e) {
console.error(e)
}
},
getCurrentCategories ({ commit }, payload) {
const newCategories = []
if (!payload) {
this.state.allItems.forEach((item) => {
if (!item.parent_id) {
newCategories.push(item)
}
})
} else {
this.state.allItems.forEach((item) => {
if (item.parent_id === payload) {
newCategories.push(item)
}
})
}
commit('setCurrentCategories', newCategories)
}
},
getters: {
allItems: s => s.allItems,
currentCategories: s => s.currentCategories
}
})
export default store
It seems like fetch method doesn't trigger at all. I tried to put something in console.log inside fetch method but I see no output in console... I'm new to nuxt, I used vue before. Any suggestions is highly appreciated.
Do this instead:
async fetch () {
await this.$store.dispatch('fetchItems')
}
If the function is not triggered it may be that its path is incorrect. Nuxt recommends using Vuex with modules: https://nuxtjs.org/docs/2.x/directory-structure/store
Each module is namespaced
.
So, in your case, I would create an items.js
file in the store directory.
And, in the layout file, I would trigger the function like this :
store.dispatch('items/fetchItems');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With