Within my dashboard, there is a dropdown for filtering dates. Each time a user changes the dropdown value, multiple network requests are sent using Axios.
To prevent additional API calls when the user rapidly changes the date filters, I utilize AbortController in JavaScript to cancel any previous pending requests.
On my VueJS component, I employ custom loading states to display loading screens based on request statuses as shown below:
Vue HTML template
<template>
<div v-if="loadingSpendingCard">
Loading...
</div>
<SpendingCard v-else/>
</template>
Vue Methods
{
...,
methods: {
fetchData(){
this.$store.dispatch("CANCEL_PENDING_REQUESTS");
this.loadingSpendingCard = true;
axiosApiClient.get("/user-spending");
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error);
})
.finally(() => {
this.loadingSpendingCard = false;
});
}
}
Using Axios request interceptors, I add an AbortController to each request and manage their states from Vuex for future cancellation. To cancel these requests, I use Vuex actions that are triggered at the start of fetchData() following this guide here.
The issue arises when the loadingSpendingCard state remains false even after aborting requests and sending new ones. It should update to true for each new request.
fetchData()
gets called every time the date filter value changes, leading to successful completion of previous requests and initiation of new ones.
I attempted keeping the state as true and not changing it if error === "canceled", which worked temporarily. However, with over 20 requests, this solution does not suffice.
fetchData(){
this.$store.dispatch("CANCEL_PENDING_REQUESTS");
this.loadingSpendingCard = true;
axiosApiClient.get("/user-spending");
.then((response) => {
console.log(response)
})
.catch((error) => {
if(error === "canceled"){
console.log("Canceled request")
}else{
this.loadingSpendingCard = false;
console.log(error);
}
})
}
Why is the loadingSpendingCard state not updating to true?