Setting Up useInfiniteQuery for Infinite Scrolling
Demonstrates the initial setup of useInfiniteQuery hook in React Query for fetching paginated data and real-time data updating as the user scrolls.
import { useInfiniteQuery } from 'react-query';
import axios from 'axios';
Import useInfiniteQuery from React Query and axios for making HTTP requests.
const fetchData = async ({ pageParam = 1 }) => {
const res = await axios.get(`https://api.example.com/data?page=${pageParam}`);
return res.data;
};
Define the fetchData function that will fetch the data from the server. It uses axios to make the GET request, receiving the pageParam to fetch specific pages.
const { data, error, fetchNextPage, hasNextPage, isFetching, isLoading } = useInfiniteQuery('data', fetchData, {
getNextPageParam: (lastPage, pages) => lastPage.nextPage,
});
Implement useInfiniteQuery hook, passing a unique string as a key, the fetchData function, and options. getNextPageParam returns the parameter needed for fetching the next page based on the last page's data.