JAVASCRIPT

Paginating API Results with Offset and Limit

Learn to paginate API results effectively by appending `offset` and `limit` parameters to your requests using JavaScript's Fetch API for controlled data retrieval.

async function fetchPaginatedData(baseUrl, offset = 0, limit = 10, options = {}) {
  const url = new URL(baseUrl);
  url.searchParams.set('_start', offset); // Example for JSONPlaceholder, or 'offset' for others
  url.searchParams.set('_limit', limit);   // Example for JSONPlaceholder, or 'limit' for others

  try {
    const response = await fetch(url.toString(), options);

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`Pagination error! Status: ${response.status}, Message: ${errorData.message || 'Unknown error'}`);
    }

    const data = await response.json();
    // Some APIs might return total count in headers (e.g., X-Total-Count)
    const totalCount = response.headers.get('X-Total-Count'); 

    return {
      data,
      totalCount: totalCount ? parseInt(totalCount, 10) : undefined,
      nextOffset: offset + limit,
      hasMore: totalCount ? (offset + limit < parseInt(totalCount, 10)) : (data.length === limit) // Heuristic if no totalCount
    };
  } catch (error) {
    console.error('Error fetching paginated data:', error);
    throw error;
  }
}

// Example usage:
// const postsApiUrl = 'https://jsonplaceholder.typicode.com/posts';
//
// (async () => {
//   console.log('Fetching first page (offset 0, limit 5):');
//   let page1 = await fetchPaginatedData(postsApiUrl, 0, 5);
//   console.log('Page 1 data:', page1.data);
//   console.log('Page 1 total count:', page1.totalCount);
//   console.log('Page 1 has more:', page1.hasMore);
//
//   if (page1.hasMore) {
//     console.log('
Fetching second page (offset 5, limit 5):');
//     let page2 = await fetchPaginatedData(postsApiUrl, page1.nextOffset, 5);
//     console.log('Page 2 data:', page2.data);
//     console.log('Page 2 total count:', page2.totalCount);
//     console.log('Page 2 has more:', page2.hasMore);
//   }
// })();
How it works: This snippet demonstrates how to implement client-side pagination when interacting with an API that supports `offset` and `limit` (or similar, like `_start` and `_limit` for JSONPlaceholder) query parameters. It constructs the URL by appending these parameters, makes the `fetch` request, and parses the response. The function also attempts to extract a total count from a common `X-Total-Count` response header, which is crucial for building pagination UI, and provides `nextOffset` and `hasMore` indicators, enabling efficient retrieval of large datasets.

Need help integrating this into your project?

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

Hire DigitalCodeLabs