JAVASCRIPT
Implement API Pagination with Vanilla JavaScript
Learn how to fetch and display paginated data from a REST API using vanilla JavaScript, including managing current page, total pages, and navigation controls.
<div id="app">
<ul id="data-list"></ul>
<div id="pagination-controls">
<button id="prev-btn" disabled>Previous</button>
<span id="page-info">Page 1 of 1</span>
<button id="next-btn">Next</button>
</div>
</div>
<script>
const dataList = document.getElementById('data-list');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
const pageInfo = document.getElementById('page-info');
const API_BASE_URL = 'https://api.example.com/items'; // Replace with your API endpoint
const ITEMS_PER_PAGE = 5;
let currentPage = 1;
let totalPages = 1;
async function fetchData(page) {
try {
const response = await fetch(`${API_BASE_URL}?page=${page}&limit=${ITEMS_PER_PAGE}`);
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
const data = await response.json();
// Assuming the API returns data in a 'results' array and total count/pages
// Adjust these lines based on your API's actual response structure
const items = data.results || data; // Or directly 'data' if it's the array
const totalItems = data.totalItems || 0; // Or from 'response.headers'
totalPages = Math.ceil(totalItems / ITEMS_PER_PAGE);
if (totalPages === 0) totalPages = 1; // Handle empty results
renderData(items);
updatePaginationControls();
} catch (error) {
console.error('Error fetching data:', error);
dataList.innerHTML = '<li>Failed to load data.</li>';
}
}
function renderData(items) {
dataList.innerHTML = '';
if (items.length === 0) {
dataList.innerHTML = '<li>No items found.</li>';
return;
}
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item.name || `Item ID: ${item.id}`; // Adjust based on item structure
dataList.appendChild(li);
});
}
function updatePaginationControls() {
pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
prevBtn.disabled = currentPage === 1;
nextBtn.disabled = currentPage === totalPages;
}
prevBtn.addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
fetchData(currentPage);
}
});
nextBtn.addEventListener('click', () => {
if (currentPage < totalPages) {
currentPage++;
fetchData(currentPage);
}
});
// Initial fetch on page load
fetchData(currentPage);
</script>
How it works: This snippet demonstrates how to implement client-side pagination for data fetched from a REST API using pure JavaScript. It defines `fetchData` to make requests with `page` and `limit` parameters. The `renderData` function updates the UI with the fetched items, and `updatePaginationControls` enables or disables the 'Previous' and 'Next' buttons based on the current page and total pages. Event listeners on the buttons trigger `fetchData` with the updated page number, creating a dynamic pagination experience. Remember to adjust `API_BASE_URL` and the data parsing logic to match your specific API's response structure.