0
Fork 0
mirror of https://github.com/TanStack/query.git synced 2026-11-16 22:50:20 +00:00
query/docs/framework/react/reference/functions/useInfiniteQuery.md
Wonsuk Choi d169ee8778
docs(*): add property tables and overload overviews to reference pages and keep declared alias names (#11758)
* docs(*): add parameter and result property tables to reference function pages and an overview to overloaded ones

* docs(*): link to the base type's properties when a parameter or result type has no property table

* docs(framework/*/reference): regenerate reference docs

* docs(framework/*/reference): regenerate reference docs

* chore(scripts/generate-docs): restore the 'dirname' import that the merge dropped

* docs(framework/*/reference): regenerate reference docs

* docs(scripts/generate-docs): label overloads in the overview with their declared parameter and return types

* docs(framework/*/reference): regenerate reference docs

* docs(scripts/generate-docs): convert declared intersection types from the source so signatures keep their alias names

* docs(framework/*/reference): regenerate reference docs

* docs(scripts/generate-docs): reword a comment to avoid the unknown word 'inlines'

* docs(scripts/generate-docs): skip a parameter table on overloaded pages when its heading is missing
2026-10-06 02:38:27 +09:00

38 KiB

id title redirect_from
useInfiniteQuery useInfiniteQuery
framework/react/reference/useInfiniteQuery

Overview

function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): DefinedUseInfiniteQueryResult<TData, TError>;
function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;
function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;

See also: Parameters · Returns

Call Signature

function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): DefinedUseInfiniteQueryResult<TData, TError>;

Defined in: packages/react-query/src/useInfiniteQuery.ts:63

The options for useInfiniteQuery are identical to useQuery, with the addition of initialPageParam, getNextPageParam, getPreviousPageParam, and maxPages.

This overload is selected when initialData is set.

Type Parameters

TQueryFnData

TQueryFnData

TError

TError = Error

TData

TData = InfiniteData<TQueryFnData, unknown>

TQueryKey

TQueryKey extends readonly unknown[] = readonly unknown[]

TPageParam

TPageParam = unknown

Parameters

options

DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>

The DefinedInitialDataInfiniteOptions to use — everything you can pass to useInfiniteQuery, with initialData set.

queryClient?

QueryClient

Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.

Returns

DefinedUseInfiniteQueryResult<TData, TError>

The same properties as useQuery, with the addition of fetchNextPage, fetchPreviousPage, hasNextPage, hasPreviousPage, isFetchingNextPage, and isFetchingPreviousPage. data.pages and data.pageParams are also added, as long as a select doesn't change TData away from its default InfiniteData<TQueryFnData> shape.

Remarks

Keep in mind that imperative fetch calls, such as fetchNextPage, may interfere with the default refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user actions, or add conditions like hasNextPage && !isFetching.

See

infiniteQueryOptions to share these options between useInfiniteQuery and imperative APIs like queryClient.infiniteQuery.

Example

import { useInfiniteQuery } from '@tanstack/react-query'

function Projects() {
  // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
  // list stays visible alongside the error.
  const { data, isError, error } = useInfiniteQuery({
    queryKey: ['projects'],
    queryFn: ({ pageParam }) => fetchProjects(pageParam),
    initialPageParam: 0,
    getNextPageParam: (lastPage) => lastPage.nextId,
    initialData: { pages: [], pageParams: [] },
  })

  return (
    <div>
      {isError ? <span>Error: {error.message}</span> : null}
      <ul>
        {data.pages.map((page) => page.projects.map((p) => <li key={p.id}>{p.name}</li>))}
      </ul>
    </div>
  )
}

Call Signature

function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;

Defined in: packages/react-query/src/useInfiniteQuery.ts:186

The options for useInfiniteQuery are identical to useQuery, with the addition of initialPageParam, getNextPageParam, getPreviousPageParam, and maxPages.

Type Parameters

TQueryFnData

TQueryFnData

TError

TError = Error

TData

TData = InfiniteData<TQueryFnData, unknown>

TQueryKey

TQueryKey extends readonly unknown[] = readonly unknown[]

TPageParam

TPageParam = unknown

Parameters

options

UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>

The UndefinedInitialDataInfiniteOptions to use — everything you can pass to useInfiniteQuery.

queryClient?

QueryClient

Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.

Returns

UseInfiniteQueryResult<TData, TError>

The same properties as useQuery, with the addition of fetchNextPage, fetchPreviousPage, hasNextPage, hasPreviousPage, isFetchingNextPage, and isFetchingPreviousPage. data.pages and data.pageParams are also added, as long as a select doesn't change TData away from its default InfiniteData<TQueryFnData> shape.

Remarks

Keep in mind that imperative fetch calls, such as fetchNextPage, may interfere with the default refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user actions, or add conditions like hasNextPage && !isFetching.

See

infiniteQueryOptions to share these options between useInfiniteQuery and imperative APIs like queryClient.infiniteQuery.

Examples

Fetching the next page from a "Load More" button click:

import { useInfiniteQuery } from '@tanstack/react-query'

function Projects() {
  const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
    useInfiniteQuery({
      queryKey: ['projects'],
      queryFn: ({ pageParam }) => fetchProjects(pageParam),
      initialPageParam: 0,
      getNextPageParam: (lastPage) => lastPage.nextId,
    })

  if (isPending) return 'Loading...'
  if (isError) return <span>Error: {error.message}</span>

  return (
    <>
      <ul>
        {data.pages.map((page) =>
          page.projects.map((project) => <li key={project.id}>{project.name}</li>),
        )}
      </ul>
      <button
        onClick={() => fetchNextPage()}
        disabled={!hasNextPage || isFetching}
      >
        {isFetchingNextPage
          ? 'Loading more...'
          : hasNextPage
            ? 'Load More'
            : 'Nothing more to load'}
      </button>
    </>
  )
}

Fetching the next page automatically as the user scrolls, using an IntersectionObserver on a sentinel element after the list:

import { useInfiniteQuery } from '@tanstack/react-query'
import { useEffect, useRef } from 'react'

function Projects() {
  const {
    data,
    isPending,
    isError,
    error,
    fetchNextPage,
    hasNextPage,
    isFetching,
    isFetchingNextPage,
  } = useInfiniteQuery({
    queryKey: ['projects'],
    queryFn: ({ pageParam }) => fetchProjects(pageParam),
    initialPageParam: 0,
    getNextPageParam: (lastPage) => lastPage.nextId,
  })

  const sentinelRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const sentinel = sentinelRef.current
    if (sentinel == null || !hasNextPage || isFetching) return

    const observer = new IntersectionObserver(([entry]) => {
      if (entry?.isIntersecting) fetchNextPage()
    })
    observer.observe(sentinel)

    return () => observer.disconnect()
  }, [hasNextPage, isFetching, fetchNextPage])

  if (isPending) return 'Loading...'
  if (isError) return <span>Error: {error.message}</span>

  return (
    <>
      <ul>
        {data.pages.map((page) =>
          page.projects.map((project) => <li key={project.id}>{project.name}</li>),
        )}
      </ul>
      <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
    </>
  )
}

Call Signature

function useInfiniteQuery<TQueryFnData, TError, TData, TQueryKey, TPageParam>(options: UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, queryClient?: QueryClient): UseInfiniteQueryResult<TData, TError>;

Defined in: packages/react-query/src/useInfiniteQuery.ts:338

The options for useInfiniteQuery are identical to useQuery, with the addition of initialPageParam, getNextPageParam, getPreviousPageParam, and maxPages.

Type Parameters

TQueryFnData

TQueryFnData

TError

TError = Error

TData

TData = InfiniteData<TQueryFnData, unknown>

TQueryKey

TQueryKey extends readonly unknown[] = readonly unknown[]

TPageParam

TPageParam = unknown

Parameters

options

UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>

The UseInfiniteQueryOptions to use — everything you can pass to useInfiniteQuery.

queryClient?

QueryClient

Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.

Returns

UseInfiniteQueryResult<TData, TError>

The same properties as useQuery, with the addition of fetchNextPage, fetchPreviousPage, hasNextPage, hasPreviousPage, isFetchingNextPage, and isFetchingPreviousPage. data.pages and data.pageParams are also added, as long as a select doesn't change TData away from its default InfiniteData<TQueryFnData> shape.

Remarks

Keep in mind that imperative fetch calls, such as fetchNextPage, may interfere with the default refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user actions, or add conditions like hasNextPage && !isFetching.

See

infiniteQueryOptions to share these options between useInfiniteQuery and imperative APIs like queryClient.infiniteQuery.

Examples

Fetching the next page from a "Load More" button click:

import { useInfiniteQuery } from '@tanstack/react-query'

function Projects() {
  const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } =
    useInfiniteQuery({
      queryKey: ['projects'],
      queryFn: ({ pageParam }) => fetchProjects(pageParam),
      initialPageParam: 0,
      getNextPageParam: (lastPage) => lastPage.nextId,
    })

  if (isPending) return 'Loading...'
  if (isError) return <span>Error: {error.message}</span>

  return (
    <>
      <ul>
        {data.pages.map((page) =>
          page.projects.map((project) => <li key={project.id}>{project.name}</li>),
        )}
      </ul>
      <button
        onClick={() => fetchNextPage()}
        disabled={!hasNextPage || isFetching}
      >
        {isFetchingNextPage
          ? 'Loading more...'
          : hasNextPage
            ? 'Load More'
            : 'Nothing more to load'}
      </button>
    </>
  )
}

Fetching the next page automatically as the user scrolls, using an IntersectionObserver on a sentinel element after the list:

import { useInfiniteQuery } from '@tanstack/react-query'
import { useEffect, useRef } from 'react'

function Projects() {
  const {
    data,
    isPending,
    isError,
    error,
    fetchNextPage,
    hasNextPage,
    isFetching,
    isFetchingNextPage,
  } = useInfiniteQuery({
    queryKey: ['projects'],
    queryFn: ({ pageParam }) => fetchProjects(pageParam),
    initialPageParam: 0,
    getNextPageParam: (lastPage) => lastPage.nextId,
  })

  const sentinelRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const sentinel = sentinelRef.current
    if (sentinel == null || !hasNextPage || isFetching) return

    const observer = new IntersectionObserver(([entry]) => {
      if (entry?.isIntersecting) fetchNextPage()
    })
    observer.observe(sentinel)

    return () => observer.disconnect()
  }, [hasNextPage, isFetching, fetchNextPage])

  if (isPending) return 'Loading...'
  if (isError) return <span>Error: {error.message}</span>

  return (
    <>
      <ul>
        {data.pages.map((page) =>
          page.projects.map((project) => <li key={project.id}>{project.name}</li>),
        )}
      </ul>
      <div ref={sentinelRef}>{isFetchingNextPage ? 'Loading more...' : null}</div>
    </>
  )
}

A query that's disabled, type safe, until postId is set — pass skipToken as queryFn instead of setting enabled: false:

import { skipToken, useInfiniteQuery } from '@tanstack/react-query'

function Comments({ postId }: { postId: string | undefined }) {
  // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled.
  const { data, isLoading, isError, error } = useInfiniteQuery({
    queryKey: ['post', postId, 'comments'],
    queryFn:
      postId != null
        ? ({ pageParam }) => fetchComments(postId, pageParam)
        : skipToken,
    initialPageParam: 0,
    getNextPageParam: (lastPage) => lastPage.nextId,
  })

  if (postId == null) return 'Select a post'
  if (isLoading) return 'Loading...'
  if (isError) return <span>Error: {error.message}</span>

  return (
    <ul>
      {data?.pages.map((page) => page.comments.map((c) => <li key={c.id}>{c.text}</li>))}
    </ul>
  )
}

Parameters

options

UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>

The UseInfiniteQueryOptions to use — everything you can pass to useInfiniteQuery.

options properties

Property Type Default value Description
enabled? | false | true | ((query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>) => boolean) true Set this to false or a function that returns false to disable automatic refetching when the query mounts or changes query keys. To refetch the query, use the refetch method returned from the useQuery instance. Accepts a boolean or function that returns a boolean.
gcTime? number undefined The time in milliseconds that unused/inactive cache data remains in memory. When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. When different garbage collection times are specified, the longest one will be used. Setting it to Infinity will disable garbage collection. Defaults to 5 * 60 * 1000 (5 minutes), or Infinity during SSR. Note: the maximum allowed time is about 24 days, imposed by setTimeout's 32-bit signed integer delay — see timeoutManager.setTimeoutProvider for a workaround.
getNextPageParam (lastPage: TQueryFnData, allPages: TQueryFnData[], lastPageParam: TPageParam, allPageParams: TPageParam[]) => TPageParam | null | undefined undefined This function can be set to automatically get the next cursor for infinite queries. The result will also be used to determine the value of hasNextPage.
getPreviousPageParam? (firstPage: TQueryFnData, allPages: TQueryFnData[], firstPageParam: TPageParam, allPageParams: TPageParam[]) => TPageParam | null | undefined undefined This function can be set to automatically get the previous cursor for infinite queries. The result will also be used to determine the value of hasPreviousPage.
initialData? | InfiniteData<TQueryFnData, TPageParam> | (() => | InfiniteData<TQueryFnData, TPageParam> | undefined) undefined If set, this value will be used as the initial data for the query cache (as long as the query hasn't been created or cached yet). If set to a function, the function will be called once during the shared/root query initialization, and be expected to synchronously return the initial data. Initial data is considered stale by default unless a staleTime has been set. initialData is persisted to the cache.
initialDataUpdatedAt? number | (() => number | undefined) undefined If set, this value will be used as the time (in milliseconds) of when the initialData itself was last updated.
initialPageParam TPageParam undefined The page param to start from when an infinite query has no pages yet. It is passed to queryFn as pageParam for the first page; every page after that gets the value returned by getNextPageParam or getPreviousPageParam. It only applies while the query has no pages: once a first page exists, refetching starts from that page's own param instead.
maxPages? number undefined Maximum number of pages to store in the data of an infinite query.
meta? Record<string, unknown> undefined Additional payload to be stored on each query. Use this property to pass information that can be used in other places.
networkMode? "online" | "always" | "offlineFirst" 'online' Controls whether a query is allowed to run based on the current network connectivity. See Network Mode for more information.
notifyOnChangeProps? | ( | "error" | "data" | "isError" | "isPending" | "isLoading" | "isLoadingError" | "isRefetchError" | "isSuccess" | "isPlaceholderData" | "status" | "dataUpdatedAt" | "errorUpdatedAt" | "failureCount" | "failureReason" | "errorUpdateCount" | "isFetched" | "isFetchedAfterMount" | "isFetching" | "isInitialLoading" | "isPaused" | "isRefetching" | "isStale" | "isEnabled" | "refetch" | "fetchStatus" | "fetchNextPage" | "fetchPreviousPage" | "hasNextPage" | "hasPreviousPage" | "isFetchNextPageError" | "isFetchingNextPage" | "isFetchPreviousPageError" | "isFetchingPreviousPage")[] | "all" | (() => | "all" | ( | "error" | "data" | "isError" | "isPending" | "isLoading" | "isLoadingError" | "isRefetchError" | "isSuccess" | "isPlaceholderData" | "status" | "dataUpdatedAt" | "errorUpdatedAt" | "failureCount" | "failureReason" | "errorUpdateCount" | "isFetched" | "isFetchedAfterMount" | "isFetching" | "isInitialLoading" | "isPaused" | "isRefetching" | "isStale" | "isEnabled" | "refetch" | "fetchStatus" | "fetchNextPage" | "fetchPreviousPage" | "hasNextPage" | "hasPreviousPage" | "isFetchNextPageError" | "isFetchingNextPage" | "isFetchPreviousPageError" | "isFetchingPreviousPage")[] | undefined) undefined If set, the component will only re-render if any of the listed properties change. When set to ['data', 'error'], the component will only re-render when the data or error properties change. When set to 'all', the component will re-render whenever a query is updated. When set to a function, the function will be executed to compute the list of properties. Defaults to undefined, in which case property access is tracked automatically, and the component only re-renders when one of the tracked properties changes.
persister? (queryFn: (context: QueryFunctionContext<NoInfer<TQueryKey>, TPageParam>) => TQueryFnData | Promise<TQueryFnData>, context: object, query: Query) => TQueryFnData | Promise<TQueryFnData> undefined This option can be used to persist the result of a query to an external storage, bypassing the need to actually call the queryFn. Useful for persisting a query's data across e.g. server/client boundaries.
placeholderData? | InfiniteData<TQueryFnData, TPageParam> | ((previousData: | InfiniteData<TQueryFnData, TPageParam> | undefined, previousQuery: | Query<InfiniteData<TQueryFnData, TPageParam>, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey> | undefined) => | InfiniteData<TQueryFnData, TPageParam> | undefined) undefined If set, this value will be used as the placeholder data for this particular query observer while the query is still in the loading data and no initialData has been provided.
queryFn? | typeof skipToken | ((context: QueryFunctionContext<TQueryKey, TPageParam>) => TQueryFnData | Promise<TQueryFnData>) undefined The function that the query will use to request data. Required, unless a default query function has been set via queryClient.setQueryDefaults or queryClient.setDefaultOptions. Receives a QueryFunctionContext. Must return a promise that will either resolve data or throw an error. The data cannot be undefined.
queryHash? string undefined The hashed form of queryKey, computed with queryKeyHashFn (or the default hashing function otherwise). Used as the actual cache key internally.
queryKey TQueryKey & object undefined The query key to use for this query. The query key will be hashed into a stable hash. See Query Keys for more information. The query will automatically update when this key changes (as long as enabled is not set to false).
queryKeyHashFn? (queryKey: TQueryKey) => string undefined If specified, this function is used to hash the queryKey to a string.
refetchInterval? | number | false | ((query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>) => number | false | undefined) false If set to a number, the query will continuously refetch at this frequency in milliseconds. If set to a function, the function will be executed with the latest data and query to compute a frequency
refetchIntervalInBackground? boolean false If set to true, the query will continue to refetch while their tab/window is in the background.
refetchOnMount? | boolean | "always" | ((query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>) => boolean | "always") true If set to true, the query will refetch on mount if the data is stale. If set to false, will disable additional instances of a query to trigger background refetch. If set to 'always', the query will always refetch on mount (except when staleTime: 'static' is used). If set to a function, the function will be executed with the latest data and query to compute the value
refetchOnReconnect? | boolean | "always" | ((query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>) => boolean | "always") undefined If set to true, the query will refetch on reconnect if the data is stale. If set to false, the query will not refetch on reconnect. If set to 'always', the query will always refetch on reconnect (except when staleTime: 'static' is used). If set to a function, the function will be executed with the latest data and query to compute the value. Defaults to true unless networkMode is 'always'.
refetchOnWindowFocus? | boolean | "always" | ((query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>) => boolean | "always") true If set to true, the query will refetch on window focus if the data is stale. If set to false, the query will not refetch on window focus. If set to 'always', the query will always refetch on window focus (except when staleTime: 'static' is used). If set to a function, the function will be executed with the latest data and query to compute the value.
retry? | number | false | true | ((failureCount: number, error: TError) => boolean) undefined If false, failed queries will not retry by default. If true, failed queries will retry infinitely. If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. If set to a function (failureCount, error) => boolean failed queries will retry until the function returns false. Defaults to 3 on the client and 0 on the server.
retryDelay? number | ((failureCount: number, error: TError) => number) undefined This function receives a retryAttempt integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. A function like attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000) applies exponential backoff. A function like attempt => attempt * 1000 applies linear backoff. Defaults to a function that applies exponential backoff, capped at 30 seconds.
retryOnMount? | false | true | ((query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>) => boolean) true If set to false, the query will not be retried on mount if it contains an error. If set to a function, the function will be executed with the query to compute the value.
select? (data: InfiniteData) => TData undefined This option can be used to transform or select a part of the data returned by the query function. It affects the returned data value, but does not affect what gets stored in the query cache. The select function will only run if data changed, or if the reference to the select function itself changes. To optimize, memoize the function so its reference stays stable across calls.
staleTime? | number | "static" | ((query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>) => number | "static") 0 The time in milliseconds after data is considered stale. If set to Infinity, the data will never be considered stale. If set to 'static', the data will never be considered stale. If set to a function, the function will be executed with the query to compute a staleTime.
structuralSharing? boolean | ((oldData: unknown, newData: unknown) => unknown) true Set this to false to disable structural sharing between query results. Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic.
subscribed? boolean true Set this to false to unsubscribe this observer from updates to the query cache.
throwOnError? | false | true | ((error: TError, query: Query<TQueryFnData, TError, InfiniteData<TQueryFnData, TPageParam>, TQueryKey>) => boolean) false Whether errors should be thrown instead of setting the error property. If set to true or suspense is true, all errors will be thrown to the error boundary. If set to false and suspense is false, errors are returned as state. If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (true) or return the error as state (false).

queryClient?

QueryClient

Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.

Returns

UseInfiniteQueryResult<TData, TError>

The same properties as useQuery, with the addition of fetchNextPage, fetchPreviousPage, hasNextPage, hasPreviousPage, isFetchingNextPage, and isFetchingPreviousPage. data.pages and data.pageParams are also added, as long as a select doesn't change TData away from its default InfiniteData<TQueryFnData> shape.

Result properties

Property Type Description
data TData | undefined The last successfully resolved data for the query.
dataUpdatedAt number The timestamp for when the query most recently returned the status as "success".
error TError | null The error object for the query, if an error was thrown. - Defaults to null.
errorUpdateCount number The sum of all errors.
errorUpdatedAt number The timestamp for when the query most recently returned the status as "error".
failureCount number The failure count for the query. - Incremented every time the query fails. - Reset to 0 when the query succeeds.
failureReason TError | null The failure reason for the query retry. - Reset to null when the query succeeds.
fetchNextPage (options?: FetchNextPageOptions) => Promise<InfiniteQueryObserverResult<TData, TError>> This function allows you to fetch the next "page" of results.
fetchPreviousPage (options?: FetchPreviousPageOptions) => Promise<InfiniteQueryObserverResult<TData, TError>> This function allows you to fetch the previous "page" of results.
fetchStatus "fetching" | "paused" | "idle" The fetch status of the query. - fetching: Is true whenever the queryFn is executing, which includes initial pending as well as background refetch. - paused: The query wanted to fetch, but has been paused. - idle: The query is not fetching. - See Network Mode for more information.
hasNextPage boolean Will be true if there is a next page to be fetched (known via the getNextPageParam option).
hasPreviousPage boolean Will be true if there is a previous page to be fetched (known via the getPreviousPageParam option).
isEnabled boolean true if this observer is enabled, false otherwise.
isError boolean A derived boolean from the status variable, provided for convenience. - true if the query attempt resulted in an error.
isFetched boolean Will be true if the query has been fetched.
isFetchedAfterMount boolean Will be true if the query has been fetched after the component mounted. - This property can be used to not show any previously cached data.
isFetching boolean A derived boolean from the fetchStatus variable, provided for convenience. - true whenever the queryFn is executing, which includes initial pending as well as background refetch.
isFetchingNextPage boolean Will be true while fetching the next page with fetchNextPage.
isFetchingPreviousPage boolean Will be true while fetching the previous page with fetchPreviousPage.
isFetchNextPageError boolean Will be true if the query failed while fetching the next page.
isFetchPreviousPageError boolean Will be true if the query failed while fetching the previous page.
isInitialLoading boolean Deprecated isInitialLoading is being deprecated in favor of isLoading and will be removed in the next major version.
isLoading boolean Is true whenever the first fetch for a query is in-flight. - Is the same as isFetching && isPending.
isLoadingError boolean Will be true if the query failed while fetching for the first time.
isPaused boolean A derived boolean from the fetchStatus variable, provided for convenience. - The query wanted to fetch, but has been paused.
isPending boolean Will be pending if there's no cached data and no query attempt was finished yet.
isPlaceholderData boolean Will be true if the data shown is the placeholder data.
isRefetchError boolean Will be true if the query failed while refetching.
isRefetching boolean Is true whenever a background refetch is in-flight, which does not include initial pending. - Is the same as isFetching && !isPending.
isStale boolean Will be true if the data in the cache is invalidated or if the data is older than the given staleTime.
isSuccess boolean A derived boolean from the status variable, provided for convenience. - true if the query has received a response with no errors and is ready to display its data.
refetch (options?: RefetchOptions) => Promise<QueryObserverResult<TData, TError>> A function to manually refetch the query.
status "error" | "pending" | "success" The status of the query. - Will be: - pending if there's no cached data and no query attempt was finished yet. - error if the query attempt resulted in an error. - success if the query has received a response with no errors and is ready to display its data.