For my project I'm using Nuxt. In the store's action I have this piece of code:
async nuxtServerInit({ commit }) {
this.dispatch('fetchAllClients')
},
async fetchAllClients({ commit, state }) {
console.log('fetch clients')
await fetch('http://localhost:1337/api/clients', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((res) => commit('storeClients', res))
},
So, on Nuxt init I would like some fetches to be run, so it can update some states (this is done in de storeClients()
which is committed in the fetch). If I copy the fetchAllClients()
method inside the nuxtServerInit()
then everything works just fine.
async nuxtServerInit({ commit }) {
await fetch('http://localhost:1337/api/clients', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((res) => commit('storeClients', res))
},
But when I call a separate method as shown in the code above, then fetch won't work. The log is shown, so the method is called properly. But somehow the fetch doesn't do anything. What am I doing wrong?
CodePudding user response:
You should have this instead
async nuxtServerInit({ dispatch }) {
await dispatch('fetchAllClients')
}