Async/await With Vuex Dispatch
I am making a loader for some components in my app. Here is my component: mounted() { this.loading = true; this.getProduct(); }, me
Solution 1:
Change this:
getProducts({commit}, type) {
axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
To this:
getProducts({commit}, type) {
return axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
Should work.
axios.get
returns a promise. You would need to return that promise in order to let await
wait for it. Otherwise, you are implicitly returning undefined
and await undefined
would immediately resolve.
Solution 2:
You can not await a function without promise
awaitthis.$store.dispatch('product/getProducts', 'bestseller');
This function return data or call new action
getProducts({commit}, type) {
axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
And this function return promise because of async function
asyncfunctionreturn promise
asyncgetProducts({commit}, type) {
let res = await axios.get(`/api/products/${type}`);
commit('SET_PRODUCTS', {products: res.data, type});
}
Now using above function now you can use
awaitthis.$store.dispatch('product/getProducts', 'bestseller');
with await key word Or you can return axios because axios also return a promise.
Post a Comment for "Async/await With Vuex Dispatch"