Blog>
Snippets

Fetching paginated data using useInfiniteQuery in React Query

Demonstrate fetching paginated data from an API using the useInfiniteQuery hook, including loading more data when the user reaches the bottom of a list.
import { useInfiniteQuery } from 'react-query';
import axios from 'axios';
Imports necessary functions and libraries.
const fetchPosts = async ({ pageParam = 1 }) => {
  const res = await axios.get(`/posts?page=${pageParam}`);
  return res.data;
};
Defines an asynchronous function to fetch posts, using axios to perform a GET request. It uses pageParam for pagination. The default value of pageParam is 1.
const { data, fetchNextPage, hasNextPage, isLoading, isError } = useInfiniteQuery(
    'posts',
    fetchPosts,
    {
        getNextPageParam: (lastPage, pages) => lastPage.nextPage || undefined
    }
);
Sets up the useInfiniteQuery hook. The query key is 'posts' and it uses the fetchPosts function to get data. getNextPageParam function is used to determine the next page's param based on the last loaded page's data.
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>An error has occurred</div>;
return (
  <div>
    {data.pages.map(page => page.results.map(post => <div key={post.id}>{post.title}</div>))}
    {hasNextPage && <button onClick={() => fetchNextPage()}>Load More</button>}
  </div>
);
Renders the fetched data. It maps through each page of data and then through each post in the page, displaying the post's title. If there is a next page (hasNextPage is true), a 'Load More' button is shown which, when clicked, triggers fetchNextPage to load more data.