const {
fetchNextPage,
fetchPreviousPage,
hasNextPage,
hasPreviousPage,
isFetchingNextPage,
isFetchingPreviousPage,
promise,
...result
} = useInfiniteQuery(() => {
queryKey,
queryFn: ({ pageParam }) => fetchPage(pageParam),
initialPageParam: 1,
...options,
getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>
lastPage.nextCursor,
getPreviousPageParam: (firstPage, allPages, firstPageParam, allPageParams) =>
firstPage.prevCursor,
})Options
The options for useInfiniteQuery are identical to the useQuery hook with the addition of the following:
queryFn: (context: QueryFunctionContext) => Promise<TData>
initialPageParam: TPageParam
getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) => TPageParam | undefined | null
getPreviousPageParam: (firstPage, allPages, firstPageParam, allPageParams) => TPageParam | undefined | null
maxPages: number | undefined
The maximum number of pages to store in the infinite query data.
When the maximum number of pages is reached, fetching a new page will result in the removal of either the first or last page from the pages array, depending on the specified direction.
If undefined or equals 0, the number of pages is unlimited
Default value is undefined
getNextPageParam and getPreviousPageParam must be properly defined if maxPages value is greater than 0 to allow fetching a page in both directions when needed.
Returns
The returned properties for useInfiniteQuery are identical to the useQuery hook, with the addition of the following properties and a small difference in isRefetching and isRefetchError:
data.pages: TData[]
data.pageParams: unknown[]
isFetchingNextPage: boolean
isFetchingPreviousPage: boolean
fetchNextPage: (options?: FetchNextPageOptions) => Promise<UseInfiniteQueryResult>
fetchPreviousPage: (options?: FetchPreviousPageOptions) => Promise<UseInfiniteQueryResult>
hasNextPage: boolean
hasPreviousPage: boolean
isFetchNextPageError: boolean
isFetchPreviousPageError: boolean
isRefetching: boolean
isRefetchError: boolean
promise: Promise<TData>
A stable promise that resolves to the query result.
This can be used with React.use() to fetch data
Requires the experimental_prefetchInRender feature flag to be enabled on the QueryClient.
Keep in mind that imperative fetch calls, such as fetchNextPage, may interfere with the default refetch behaviour, resulting in outdated data. Make sure to call these functions only in response to user actions, or add conditions like hasNextPage && !isFetching.