JAVASCRIPT
Handle Paginated API Responses with Dynamic URLs
Master client-side pagination by fetching and displaying data from API endpoints, dynamically managing 'next' and 'previous' page links using the 'Link' header.
async function fetchPaginatedData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Attempt to parse 'Link' header for pagination URLs
const linkHeader = response.headers.get('Link');
const paginationLinks = {};
if (linkHeader) {
linkHeader.split(',').forEach(part => {
const section = part.split(';');
if (section.length !== 2) return;
const url = section[0].replace(/<(.*)>/, '$1').trim();
const name = section[1].replace(/rel="(.*)"/, '$1').trim();
paginationLinks[name] = url;
});
}
// If API provides pagination links in the body (e.g., 'next', 'prev')
// This is common in many APIs like GitHub's or custom implementations.
// Adjust property names based on your API's response structure.
const nextLink = data.links?.next || paginationLinks.next;
const prevLink = data.links?.prev || paginationLinks.prev;
return { data, nextLink, prevLink };
} catch (error) {
console.error('Error fetching paginated data:', error);
throw error;
}
}
// Usage example:
// const initialUrl = 'https://api.example.com/items?page=1&per_page=10';
// let currentPageUrl = initialUrl;
// async function loadPage(url) {
// try {
// const { data, nextLink, prevLink } = await fetchPaginatedData(url);
// console.log('Current Page Data:', data);
// console.log('Next Page URL:', nextLink);
// console.log('Previous Page URL:', prevLink);
// // Example: Update UI with data and navigation buttons
// // if (nextLink) {
// // document.getElementById('nextButton').onclick = () => loadPage(nextLink);
// // } else { /* disable next button */ }
// // if (prevLink) {
// // document.getElementById('prevButton').onclick = () => loadPage(prevLink);
// // } else { /* disable prev button */ }
// } catch (error) {
// // Handle error in UI
// }
// }
// loadPage(currentPageUrl);
How it works: This snippet illustrates how to consume paginated API responses, a common requirement for large datasets. It fetches data from a given URL and then intelligently extracts 'next' and 'previous' page URLs. The code prioritizes parsing the 'Link' HTTP header (a standard for pagination), but also includes logic to check the response body for pagination links, which many APIs provide directly. This allows your application to dynamically navigate through pages of data, enabling 'load more' or traditional pagination UIs.