JAVASCRIPT

Fetching Paginated Data from a REST API

Learn to fetch data from a REST API endpoint that supports pagination, allowing you to load large datasets incrementally and efficiently.

async function fetchPaginatedData(baseUrl, page = 1, limit = 10) {
  try {
    const response = await fetch(`${baseUrl}?page=${page}&limit=${limit}`);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(`Page ${page} data:`, data.items); // Assuming 'items' is the data array
    
    // Check if there's a next page or total pages from the response metadata
    if (data.nextPage && data.nextPage < data.totalPages) {
      console.log(`Fetching next page: ${data.nextPage}`);
      await fetchPaginatedData(baseUrl, data.nextPage, limit); // Recursive call for next page
    } else if (data.hasNextPage && data.nextPage) { // Alternative common structure
        console.log(`Fetching next page: ${data.nextPage}`);
        await fetchPaginatedData(baseUrl, data.nextPage, limit);
    } else {
        console.log("All pages fetched.");
    }
    return data; // Return data of the current page or the first page's data
  } catch (error) {
    console.error("Error fetching paginated data:", error);
    throw error;
  }
}

// Example usage:
// Assumes an API endpoint like /api/products?page=1&limit=10
// and response contains { items: [...], totalPages: 5, nextPage: 2 }
// fetchPaginatedData('https://api.example.com/products');
How it works: This JavaScript snippet demonstrates how to fetch data from a paginated REST API. It uses `fetch` to make requests, incrementing the `page` parameter with each call. The function includes basic error handling and recursively calls itself to retrieve subsequent pages based on `nextPage` and `totalPages` properties commonly found in API responses.

Need help integrating this into your project?

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

Hire DigitalCodeLabs