Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show page loader with two or more API calls?

Tags:

reactjs

rxjs

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 />

  • 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?

like image 320
Varun Deva Avatar asked Jan 19 '26 18:01

Varun Deva


2 Answers

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

like image 175
Giorgi Moniava Avatar answered Jan 21 '26 07:01

Giorgi Moniava


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]); 
  }
);
like image 29
Salem_Raouf Avatar answered Jan 21 '26 09:01

Salem_Raouf