乐闻世界logo
搜索文章和话题

How react Infinite Queries support with offset and limit

1个答案

1

React Query's infinite query feature enables developers to implement infinite scrolling or 'load more' functionality. To set pagination parameters in infinite queries, you need to use the useInfiniteQuery hook and define a function to fetch your data pages. This function typically receives pagination information, such as the page number or the last item from the previous request.

Here is a basic example of using useInfiniteQuery to set pagination parameters.

Assume we have an API that provides data by page number, with a fixed number of items per page, and the API's pagination parameter is page:

javascript
import { useInfiniteQuery } from 'react-query'; // Assume this function handles fetching data and returns pagination information const fetchProjects = async ({ pageParam = 1 }) => { const response = await fetch('/api/projects?page=' + pageParam); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }; function Projects() { const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status, } = useInfiniteQuery( 'projects', // Query key ({ pageParam = 1 }) => fetchProjects({ pageParam }), { // The `getNextPageParam` function determines the parameter for the next page based on the current page information getNextPageParam: (lastPage, pages) => { if (lastPage.hasNextPage) { return pages.length + 1; // Assuming each page has a `hasNextPage` field } else { return undefined; // Return undefined when there are no more pages } }, } ); if (status === 'loading') { return <p>Loading...</p>; } if (status === 'error') { return <span>Error: {error.message}</span>; } return ( <> {data.pages.map((group, i) => ( <React.Fragment key={i}> {group.items.map(project => ( <p key={project.id}>{project.name}</p> ))} </React.Fragment> ))} <div> <button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage} > {isFetchingNextPage ? 'Loading more...' : hasNextPage ? 'Load More' : 'Nothing more to load'} </button> </div> <div>{isFetching && !isFetchingNextPage ? 'Fetching...' : null}</div> </> ); }

In this example, the second parameter of useInfiniteQuery is an asynchronous function that fetches data, taking an object with a pageParam property, which specifies the page number for the current request. The getNextPageParam function determines the parameter for the next page based on the current page information; if there are no more pages, it returns undefined.

When the user triggers the fetchNextPage function, React Query uses the return value of getNextPageParam as the pageParam for the next page, thereby implementing pagination queries. By doing this, developers can implement infinite scrolling or 'load more' functionality without manually managing pagination logic.

2024年6月29日 12:07 回复

你的答案