JAVASCRIPT

Fetching All Pages from a Paginated API

Efficiently retrieve all data from a paginated API endpoint using asynchronous JavaScript, handling 'next page' links or offset-based pagination.

async function fetchAllPages(initialUrl, pageParam = 'page', limitParam = 'limit') {
  let allData = [];
  let nextUrl = initialUrl;

  while (nextUrl) {
    try {
      const response = await fetch(nextUrl);
      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 a 'next' URL
      // Adjust these properties based on your API's response structure
      allData = allData.concat(data.results || data.items || []); // Combine results
      nextUrl = data.next_page || data.next || null; // Get next page URL or indicator

      // If using offset/limit pagination without a 'next' link:
      // You might need to parse the current URL and increment 'pageParam' or 'offset'
      // Example for page-based: 
      // if (!data.next && data.total_pages && data.current_page < data.total_pages) {
      //   const url = new URL(nextUrl || initialUrl);
      //   const currentPage = parseInt(url.searchParams.get(pageParam) || '1', 10);
      //   url.searchParams.set(pageParam, (currentPage + 1).toString());
      //   nextUrl = url.toString();
      // } else if (!data.next) {
      //   nextUrl = null;
      // }

    } catch (error) {
      console.error('Error fetching paginated data:', error);
      // Optionally, implement retry logic here
      break; // Stop fetching on error
    }
  }
  return allData;
}

// Example Usage:
// const apiUrl = 'https://api.example.com/products?limit=10';
// fetchAllPages(apiUrl)
//   .then(products => {
//     console.log('All products:', products.length);
//     // Process all products
//   })
//   .catch(error => {
//     console.error('Failed to fetch all products:', error);
//   });
How it works: This JavaScript snippet provides a utility function to fetch all data from a paginated API endpoint. Many APIs return data in chunks (pages) to optimize performance and manage large datasets. This function iteratively calls the API, starting from an `initialUrl`, and continues fetching subsequent pages until no `next_page` (or similar indicator like `next` link, `offset`, or `total_pages`) is provided by the API response. It collects all results into a single array, abstracting away the pagination logic from the consumer. The internal logic might need slight adjustments based on the specific pagination strategy (e.g., cursor-based, offset-based, page number-based) used by the target API.

Need help integrating this into your project?

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

Hire DigitalCodeLabs