The issue you're facing is due to the asynchronous nature of the axios.post calls within the for loop. Each API request is sent out, but the loop does not wait for each request to complete before moving on to the next iteration. As a result, the loading state is set to false before all the data has been fetched.
To fix this, you can use Promise.all to wait for all the API requests to complete before setting the loading state to false. Here's how you can modify the makeApiRequest method:
async makeApiRequest(data, url, locations) {
// Create an array to hold all the promises
let promises = [];
for (const location of locations) {
// Create a new FormData instance for each request to avoid appending to the same instance
let locationData = new FormData();
for (let [key, value] of data.entries()) {
locationData.append(key, value);
}
locationData.append("selectedPartners", location);
// Push the axios promise into the promises array
promises.push(axios.post(url, locationData));
}
try {
// Wait for all the promises to resolve
let results = await Promise.all(promises);
// Concatenate the results
for (let response of results) {
this.tempData = this.tempData.concat(response.data.data);
}
// Update the reportData and dataCount after all requests are done
this.reportData = this.tempData;
this.dataCount = this.reportData.length;
} catch (error) {
console.error("ERROR HERE: ", error.message);
} finally {
// Set loading to false only after all requests have completed
this.loading = false;
}
}
And in the getReport method, remove the this.loading = false; line since it will now be handled in the finally block of the makeApiRequest method:
async getReport(sync_api) {
if (this.loading == true) return;
this.loading = true;
const url = "/api/get_locations_details";
const data = new FormData();
data.append("from_date", this.from_date);
data.append("to_date", this.to_date);
if (sync_api == true) {
data.append("sync_api", 1);
}
if (this.selectedLocations) {
try {
await this.makeApiRequest(data, url, this.selectedLocations);
if (sync_api == true) {
this.$store.dispatch(
"global/snackBarState",
{
show: true,
color: "primary",
message: "Processing, Please wait few Seconds...",
},
{ root: true }
);
}
// this.loading = false; // Remove this line
this.tempData = [];
} catch (error) {
console.error("ERROR HERE: ", error.message);
}
}
}
With these changes, the loading state will only be set to false after all the API requests have been completed, ensuring that the loading animation only finishes when the entire data set is ready.