const { fetchNextPage, fetchPreviousPage, hasNextPage, hasPreviousPage, isFetchingNextPage, isFetchingPreviousPage, ...result} = useInfiniteQuery({ queryKey, queryFn: ({ pageParam = 1 }) => fetchPage(pageParam), ...options, getNextPageParam: (lastPage, allPages) => lastPage.nextCursor, getPreviousPageParam: (firstPage, allPages) => firstPage.prevCursor,})
Options
The options for useInfiniteQuery
are identical to the useQuery
hook with the addition of the following:
queryFn: (context: QueryFunctionContext) => Promise<TData>
defaultQueryFn
pageParam
if needed for use in the props below.getNextPageParam: (lastPage, allPages) => unknown | undefined
undefined
to indicate there is no next page available.getPreviousPageParam: (firstPage, allPages) => unknown | undefined
undefined
to indicate there is no previous page available.Returns
The returned properties for useInfiniteQuery
are identical to the useQuery
hook, with the addition of the following and a small difference in isRefetching
:
data.pages: TData[]
data.pageParams: unknown[]
isFetchingNextPage: boolean
true
while fetching the next page with fetchNextPage
.isFetchingPreviousPage: boolean
true
while fetching the previous page with fetchPreviousPage
.fetchNextPage: (options?: FetchNextPageOptions) => Promise<UseInfiniteQueryResult>
options.pageParam: unknown
allows you to manually specify a page param instead of using getNextPageParam
.options.cancelRefetch: boolean
if set to true
, calling fetchNextPage
repeatedly will invoke fetchPage
every time, whether the previous
invocation has resolved or not. Also, the result from previous invocations will be ignored. If set to false
, calling fetchNextPage
repeatedly won't have any effect until the first invocation has resolved. Default is true
.fetchPreviousPage: (options?: FetchPreviousPageOptions) => Promise<UseInfiniteQueryResult>
options.pageParam: unknown
allows you to manually specify a page param instead of using getPreviousPageParam
.options.cancelRefetch: boolean
same as for fetchNextPage
.hasNextPage: boolean
true
if there is a next page to be fetched (known via the getNextPageParam
option).hasPreviousPage: boolean
true
if there is a previous page to be fetched (known via the getPreviousPageParam
option).isRefetching: boolean
true
whenever a background refetch is in-flight, which does not include initial loading
or fetching of next or previous pageisFetching && !isLoading && !isFetchingNextPage && !isFetchingPreviousPage
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
.
“This course is the best way to learn how to use React Query in real-world applications.”—Tanner LinsleyCheck it out