basically i created 1 state [isLoading, setIsLoading]=useState(false)
i have 3 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 2 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 />
- One solution is creating 3 states and using like
(isLoading1 || isLoading2 || isLoading3) && <Loader />
But i dont like to create multiple states like this.
Any better way to handle this Loading Animation?
CodePudding user response:
You could have a state variable like:
loadingCounter
then in each function before the callApi
increment it, and when callApi
is done, decrement it.
So if loadingCounter > 0
it means data is loading from somewhere still.
Or look into Promise.all
CodePudding user response:
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)
});