Blog>
Snippets

Using QueryKeys for Paginated Data Fetching

Provide an example of using QueryKeys to manage the fetching of paginated data, including handling next and previous page data.
import { useQuery } from 'react-query';

function fetchPaginatedData({ queryKey }) {
    const [, page] = queryKey;
    return fetch(`http://example.com/data?page=${page}`).then(res =>
        res.json()
    );
}
Defines a function to fetch paginated data from an API. The function accepts a queryKey parameter from which the current page number is extracted.
const PaginatedComponent = () => {
    const [page, setPage] = useState(1);
    const { data, isFetching, isError } = useQuery(['data', page], fetchPaginatedData, {
        keepPreviousData: true
    });

    return (
        <div>
            {isFetching && <p>Loading...</p>}
            {isError && <p>Error fetching data</p>}
            {data && (
                <div>
                    {/* Data rendering goes here */}
                </div>
            )}
            <button onClick={() => setPage(old => Math.max(old - 1, 1))} disabled={page === 1}>Previous Page</button>
            <button onClick={() => setPage(old => old + 1)} disabled={!data || data.length === 0}>Next Page</button>
        </div>
    );
}
Implements the UI component using the useQuery hook to fetch data. The page state manages pagination, and buttons are provided to navigate to the next and previous pages.