Problem:
- You have 10 APIs calling at the same time.
- You want to:
- Show a loading spinner while fetching.
- Wait until all 10 responses arrive.
- Then set
loading = falseand render content.
🔹 Best Solution → Promise.all()
👉 Promise.all() waits until all promises are resolved (or one fails).
🔹 Example (React Functional Component)
import React, { useState, useEffect } from "react";
function MultipleAPIsExample() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
// List of API URLs
const apiUrls = [
"https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/posts/2",
"https://jsonplaceholder.typicode.com/posts/3",
"https://jsonplaceholder.typicode.com/posts/4",
"https://jsonplaceholder.typicode.com/posts/5",
"https://jsonplaceholder.typicode.com/posts/6",
"https://jsonplaceholder.typicode.com/posts/7",
"https://jsonplaceholder.typicode.com/posts/8",
"https://jsonplaceholder.typicode.com/posts/9",
"https://jsonplaceholder.typicode.com/posts/10",
];
// Convert each URL into a fetch Promise
const requests = apiUrls.map((url) => fetch(url).then((res) => res.json()));
// Wait for all API calls
Promise.all(requests)
.then((responses) => {
setData(responses); // Store all responses in state
setLoading(false); // Hide loader only after all APIs resolve
})
.catch((error) => {
console.error("Error fetching data:", error);
setLoading(false); // Hide loader even if error (optional)
});
}, []);
if (loading) {
return <h2>Loading data from 10 APIs...</h2>;
}
return (
<div>
<h2>All API Data Loaded ✅</h2>
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
}
export default MultipleAPIsExample;
🔹 Explanation
apiUrls→ array of 10 API endpoints.map()→ creates an array offetch()promises.Promise.all()→ waits for all promises to resolve.- Once done → update
data& setloading = false. - While waiting → display Loading...
🔹 Alternative: Promise.allSettled()
- If one API fails,
Promise.all()rejects everything ❌. - If you still want the successful results → use
Promise.allSettled().
Promise.allSettled(requests).then((results) => {
const successData = results
.filter((r) => r.status === "fulfilled")
.map((r) => r.value);
setData(successData);
setLoading(false);
});
✅ Summary:
- Use
Promise.all()→ wait for all 10 APIs. - Use
Promise.allSettled()→ even if some fail, still get others. - Manage
loadingstate → show spinner until all done.