I'm currently working on creating a loader for specific components within my application.
Here is the code snippet for one of my components:
mounted() {
this.loading = true;
this.getProduct();
},
methods: {
async getProduct() {
await this.$store.dispatch('product/getProducts', 'bestseller');
console.log(123);
this.loading = false;
}
},
Vuex 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);
})
},
The issue lies in this line of code:
await this.$store.dispatch('product/getProducts', 'bestseller');
The expectation was that the code would pause at this line, wait for the data to be loaded from the AJAX call, and then set the loading status to false
; however, that did not happen. The loading status is still set to false
, and the console.log
statement runs before the data is fully ready.
An attempt was made to move the async/await logic into the Vuex action, which resolved the issue. However, the exact difference between the two approaches remains unclear.
Below is the updated code that successfully addressed the problem:
Component:
mounted() {
this.loading = true;
this.$store.dispatch('product/getProducts', 'bestseller').then((res) => {
this.loading = false;
});
},
Vuex action:
async getProducts({commit}, type) {
let res = await axios.get(`/api/products/${type}`);
commit('SET_PRODUCTS', {products: res.data, type});
}