function useSuspenseQuery<TQueryFnData, TError, TData, TQueryKey>(options: UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, queryClient?: QueryClient): UseSuspenseQueryResult<TData, TError>;Defined in: packages/preact-query/src/useSuspenseQuery.ts:93
The options for useSuspenseQuery are the same as for useQuery, except for throwOnError, enabled, and placeholderData.
Caveat: cancellation does not work.
TQueryFnData = unknown
TError = Error
TData = TQueryFnData
TQueryKey extends readonly unknown[] = readonly unknown[]
UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>
The UseSuspenseQueryOptions to use — the same options as useQuery, minus the ones listed above.
| Property | Type | Default value | Description |
|---|---|---|---|
| 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. |
| initialData? | TQueryFnData | (() => TQueryFnData | 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. |
| 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: object) => 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. |
| queryFn? | (context: object) => TQueryFnData | Promise<TQueryFnData> | undefined | skipToken is not allowed here — Suspense hooks cannot render a "disabled" state, so a query function must always be provided, unless a default query function has been defined. |
| 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, TQueryFnData, 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, TQueryFnData, 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, TQueryFnData, 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, TQueryFnData, 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, TQueryFnData, 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: TQueryFnData) => 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, TQueryFnData, 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. |
Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
UseSuspenseQueryResult<TData, TError>
The same object as useQuery, except that data is guaranteed to be defined, isPlaceholderData is missing, and status is either success or error (with the derived flags set accordingly).
Built from QueryObserverBaseResult. See the type above for what it changes.
Multiple useSuspenseQuery calls in the same component suspend serially, causing a request waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then. Use useSuspenseQueries instead when you have more than one suspenseful query in a component, so they fetch in parallel.
The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is required around <Suspense>. A failed background refetch instead continues to render the cached data. Use QueryErrorResetBoundary to let the user retry after such an error:
import { Suspense } from 'preact/compat'
import { useErrorBoundary } from 'preact/hooks'
import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/preact-query'
import type { ComponentChildren } from 'preact'
function Posts() {
// `data` is guaranteed to be defined here — no `isPending` check needed.
const { data, isFetching } = useSuspenseQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
})
return (
<div>
<h1>Posts {isFetching ? '(refreshing...)' : null}</h1>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
)
}
function App() {
return (
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ resetErrorBoundary }) => (
<div>
There was an error!
<button onClick={() => resetErrorBoundary()}>Try again</button>
</div>
)}
>
<Suspense fallback={<h1>Loading posts...</h1>}>
<Posts />
</Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
)
}
function ErrorBoundary({
children,
onReset,
fallbackRender,
}: {
children: ComponentChildren
onReset: () => void
fallbackRender: (props: {
error: Error
resetErrorBoundary: () => void
}) => ComponentChildren
}) {
const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
if (error) return fallbackRender({ error, resetErrorBoundary })
return children
}