Basically I created state variable
let [isLoading, setIsLoading] = useState(false)
I have three apis that need to call.
const api1 = ()=>{
setIsLoading(true)
callApi()
setIsLoading(false)
}
const api2 = ()=>{
setIsLoading(true)
callApi()
setIsLoading(false)
}
const api3 = ()=>{
setIsLoading(true)
callApi()
setIsLoading(false)
}
I call those 3 functions in useEffect() .
Using axios for calling the apis,
whenever any one of the api call is success it will set the setIsLoading() to false. So loading animation is stopped.
Still other two apis are not completed.
Basically I need to stop the loader when all the api calls are done.
In UI part im just doing isLoading && <Loader />
(isLoading1 || isLoading2 || isLoading3) && <Loader />But i dont like to create multiple states like this.
Any better way to handle this Loading Animation?
You could have a state variable like:
const [loadingCounter, setLoadingCounter] = useState(0);
then in each function before the callApi increment it, and when callApi is done (inside finally), decrement it.
So if loadingCounter > 0 it means data is loading from somewhere still.
Or look into Promise.all
You can fetch your API's with one call using Promise.all and wait for promises to be resolved
setLoading(true);
const promise1 = callAPI();
const promise2 = callAPI();
const promise3 = callAPI();
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
setLoading(false)
});
if you want to handle API fail call
Promise.all([promise1.catch((error) => error), promise2.catch((error) => error),promise3.catch((error) => error)])
.then(
(values) => {
console.log(values[0]);
console.error(values[1]);
console.error(values[2]);
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With