JAVASCRIPT

Implementing API Response Pagination on the Frontend

Efficiently manage and display large datasets from APIs by implementing frontend pagination logic, allowing users to navigate through results.

// Assuming an API that returns data and pagination links/metadata
// Example API response structure:
// {
//   "data": [...],
//   "pagination": {
//     "currentPage": 1,
//     "totalPages": 10,
//     "perPage": 10,
//     "totalItems": 100,
//     "nextPageUrl": "https://api.example.com/items?page=2&limit=10",
//     "prevPageUrl": null
//   }
// }

let currentPage = 1;
let totalPages = 1;
let itemsPerPage = 10;
let baseUrl = 'https://api.example.com/items';

async function fetchPaginatedData(page = 1) {
  try {
    const response = await fetch(`${baseUrl}?page=${page}&limit=${itemsPerPage}`);
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const result = await response.json();

    // Update global pagination state
    currentPage = result.pagination.currentPage;
    totalPages = result.pagination.totalPages;

    console.log(`Fetched Page ${currentPage} of ${totalPages}:`, result.data);
    // Render data to UI
    renderData(result.data);
    updatePaginationControls();
  } catch (error) {
    console.error('Error fetching paginated data:', error);
    // Display error message to user
  }
}

function renderData(data) {
  const container = document.getElementById('data-container');
  if (!container) return;
  container.innerHTML = ''; // Clear previous data
  data.forEach(item => {
    const div = document.createElement('div');
    div.textContent = `ID: ${item.id}, Name: ${item.name}`; // Adjust based on your API structure
    container.appendChild(div);
  });
}

function updatePaginationControls() {
  const prevButton = document.getElementById('prev-page');
  const nextButton = document.getElementById('next-page');
  const pageInfo = document.getElementById('page-info');

  if (prevButton) prevButton.disabled = currentPage === 1;
  if (nextButton) nextButton.disabled = currentPage === totalPages;
  if (pageInfo) pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
}

// Event listeners for pagination buttons
document.getElementById('prev-page')?.addEventListener('click', () => {
  if (currentPage > 1) {
    fetchPaginatedData(currentPage - 1);
  }
});

document.getElementById('next-page')?.addEventListener('click', () => {
  if (currentPage < totalPages) {
    fetchPaginatedData(currentPage + 1);
  }
});

// Initial load
// document.addEventListener('DOMContentLoaded', () => {
//   fetchPaginatedData();
// });
How it works: This snippet illustrates how to implement client-side pagination for API responses. It fetches data based on page number and items per page, updates the UI with the received data, and manages pagination controls (e.g., 'Previous'/'Next' buttons). This approach is crucial for handling large datasets efficiently, reducing load times, and improving the user experience by only fetching and displaying a subset of data at a time, rather than the entire dataset.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs