Blog>
Snippets

Fetching Paginated Data Function

Shows how to create a function that fetches paginated data from an API, suitable for connecting to the useInfiniteQuery hook for an infinite scroll feature.
const fetchPaginatedData = async ({ pageParam = 1 }) => {
  const response = await fetch(`https://api.example.com/data?page=${pageParam}&limit=10`);
  if (!response.ok) throw new Error('Network response was not ok');
  const data = await response.json();
  return { data: data.results, nextPage: data.nextPage ? pageParam + 1 : undefined };
};
This function fetches data from an API, expecting the API to support pagination through query parameters. It takes an object with a pageParam property, which defaults to 1 if not provided. This page param is used to fetch the corresponding page of data. The function assumes the API response includes a 'results' array with the data for the current page and a 'nextPage' boolean to indicate if there is a next page. It returns an object with the fetched data and the next page number if more data is available, otherwise undefined.