JAVASCRIPT
Implementing Client-Side Pagination for API Results
Implement effective client-side pagination to fetch and display data from an API page by page, improving performance and user experience for large datasets.
async function fetchPaginatedData(baseUrl, page = 1, limit = 10) {
try {
const response = await fetch(`${baseUrl}?page=${page}&limit=${limit}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(`Page ${page} data:`, data);
return data;
} catch (error) {
console.error('Error fetching paginated data:', error);
throw error;
}
}
// Example: Fetching the first page of items
// fetchPaginatedData('https://api.example.com/items', 1, 5);
// To demonstrate fetching all pages iteratively (adapt for UI interaction):
const allItems = [];
let currentPage = 1;
const itemsPerPage = 5;
let hasMore = true;
async function fetchAllPages(url) {
while (hasMore) {
const pageData = await fetchPaginatedData(url, currentPage, itemsPerPage);
if (pageData && pageData.length > 0) {
allItems.push(...pageData);
currentPage++;
// Assuming the API returns an empty array when no more data, or a 'nextPage' link/flag.
if (pageData.length < itemsPerPage) {
hasMore = false;
}
} else {
hasMore = false;
}
}
console.log('All fetched items:', allItems);
}
// Usage example for fetching all pages:
// fetchAllPages('https://api.example.com/products');
How it works: This snippet provides a flexible approach to implement client-side pagination for API results. It demonstrates how to construct API requests with `page` and `limit` query parameters, common for paginated endpoints. The `fetchPaginatedData` function shows how to retrieve a single page, while the `fetchAllPages` example illustrates a loop to iteratively fetch and accumulate data from multiple pages until no more results are available, suitable for scenarios requiring all data upfront or on user scroll.