JAVASCRIPT
Implementing Client-Side Pagination for API Data
Learn how to fetch and display paginated data from a REST API, allowing users to navigate through results with next/previous buttons to enhance user experience.
async function fetchPaginatedData(page = 1, limit = 10) {
const apiUrl = `https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=${limit}`;
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const totalCount = response.headers.get('x-total-count'); // Assuming API sends total count in header
displayData(data);
updatePaginationControls(page, limit, totalCount);
return { data, totalCount };
} catch (error) {
console.error("Failed to fetch paginated data:", error);
return { data: [], totalCount: 0 };
}
}
function displayData(items) {
const container = document.getElementById('data-container');
container.innerHTML = '';
items.forEach(item => {
const div = document.createElement('div');
div.textContent = `ID: ${item.id}, Title: ${item.title}`;
container.appendChild(div);
});
}
let currentPage = 1;
const itemsPerPage = 10;
let totalItems = 0;
function updatePaginationControls(currentPage, limit, total) {
totalItems = parseInt(total, 10);
const totalPages = Math.ceil(totalItems / limit);
document.getElementById('current-page').textContent = `Page ${currentPage} of ${totalPages}`;
document.getElementById('prev-btn').disabled = currentPage === 1;
document.getElementById('next-btn').disabled = currentPage === totalPages;
}
document.getElementById('prev-btn').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
fetchPaginatedData(currentPage, itemsPerPage);
}
});
document.getElementById('next-btn').addEventListener('click', () => {
const totalPages = Math.ceil(totalItems / itemsPerPage);
if (currentPage < totalPages) {
currentPage++;
fetchPaginatedData(currentPage, itemsPerPage);
}
});
// Initial fetch
fetchPaginatedData(currentPage, itemsPerPage);
// Example HTML structure:
// <div id="data-container"></div>
// <div>
// <button id="prev-btn">Previous</button>
// <span id="current-page"></span>
// <button id="next-btn">Next</button>
// </div>
How it works: This snippet demonstrates fetching data with client-side pagination. The `fetchPaginatedData` function takes `page` and `limit` parameters, constructing a URL to request a specific subset of data. It assumes the API returns the total number of items in the `x-total-count` response header. Functions are included to display the fetched data and to update pagination control buttons, enabling users to navigate between pages.