Blog>
Snippets

Pagination with React Query

Implement pagination in a React application using React Query, fetching and displaying pages of data with `useInfiniteQuery`.
const fetchPosts = async ({ pageParam = 1 }) => {
  const res = await fetch(`/api/posts?page=${pageParam}`);
  return res.json();
};
Defines an async function to fetch posts from an API. The pageParam parameter allows fetching posts from specific pages, defaulting to the first page if not provided.
const Posts = () => {
  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery('posts', fetchPosts, {
    getNextPageParam: (lastPage, pages) => lastPage.nextPage,
  });

  return (
    <>
      {data.pages.map((group, i) => (
        <React.Fragment key={i}>
          {group.posts.map((post) => (
            <p key={post.id}>{post.title}</p>
          ))}
        </React.Fragment>
      ))}
      <div>
        <button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}>
          {isFetchingNextPage ? 'Loading more...' : hasNextPage ? 'Load More' : 'Nothing more to load'}
        </button>
      </div>
    </>
  );
};
Implementing the Posts component which uses useInfiniteQuery hook to fetch pages of posts. It maps over the fetched data to display it and provides a 'Load More' button to fetch the next page of posts if available.