To implement paginated infinite scroll with React-Query using the useInfiniteQuery
hook, you can follow these steps:
Install React-Query: First, make sure you have React-Query installed in your project. You can install it via npm or yarn:
csharpnpm install react-query
// or
yarn add react-query
Set Up Your API Functions: You need to define a function to fetch your paginated data from the server. This function should accept a pageParam
parameter that specifies the page number to fetch.
Use useInfiniteQuery
Hook: In your React component, import useInfiniteQuery
from 'react-query'. Then, use it to fetch and manage paginated data.
Here's an example implementation:
jsximport React from 'react';
import { useInfiniteQuery } from 'react-query';
const fetchUsers = async (key, page = 1) => {
const response = await fetch(`https://api.example.com/users?page=${page}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
const UsersList = () => {
const {
data,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
error,
} = useInfiniteQuery('users', fetchUsers, {
getNextPageParam: (lastPage, allPages) => {
// Return the next page number or null if no more pages left
return lastPage.page < lastPage.totalPages ? lastPage.page + 1 : null;
},
});
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{data.pages.map(pageData => (
<React.Fragment key={pageData.page}>
{pageData.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</React.Fragment>
))}
{isFetching && <div>Loading...</div>}
{hasNextPage && (
<button
onClick={() => fetchNextPage()}
disabled={isFetchingNextPage}
>
{isFetchingNextPage ? 'Loading more...' : 'Load More'}
</button>
)}
</div>
);
};
export default UsersList;
In this example:
fetchUsers
function that fetches users from an API endpoint. It takes a page
parameter indicating the page number to fetch.useInfiniteQuery
hook to fetch paginated data. We pass it the key 'users' to identify this query, the fetchUsers
function, and a getNextPageParam
function that tells React-Query how to determine the next page number.Make sure to adjust the API endpoint and data structure according to your backend implementation.