JAVASCRIPT
Fetching Paginated Data from an API with JavaScript
Learn to efficiently fetch and concatenate data from paginated API endpoints using asynchronous JavaScript, handling 'next' links and updating UI.
async function fetchAllPaginatedData(url, allResults = []) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Assuming API returns an array in `results` and a `next` URL
const currentResults = data.results || data; // Adjust based on API structure
allResults = allResults.concat(currentResults);
if (data.next) {
// Recursively call for the next page
return await fetchAllPaginatedData(data.next, allResults);
} else {
return allResults;
}
} catch (error) {
console.error("Error fetching paginated data:", error);
throw error; // Re-throw to allow caller to handle
}
}
// Example usage:
// fetchAllPaginatedData("https://swapi.dev/api/people/")
// .then(allPeople => {
// console.log("All fetched people:", allPeople);
// // Render allPeople in your UI
// })
// .catch(err => {
// console.error("Failed to fetch all data:", err);
// });
How it works: This snippet demonstrates how to fetch all data from an API that uses pagination (e.g., with `next` links or page numbers). The `fetchAllPaginatedData` function recursively calls itself with the URL for the next page until no further pages are indicated, accumulating all results into a single array. This approach is essential for APIs that limit the number of records returned per request.