Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useSuspenseQuery.ts

101 lines3.6 KB

1'use client'
2import { QueryObserver, skipToken } from '@tanstack/query-core'
3import { useBaseQuery } from './useBaseQuery'
4import { defaultThrowOnError } from './suspense'
5import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
6import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
7​
8/**
9 * The options for `useSuspenseQuery` are the same as for `useQuery`, except for `throwOnError`, `enabled`, and
10 * `placeholderData` β€” and `queryFn` may not be `skipToken`, since Suspense hooks can't render a "disabled" state.
11 *
12 * Caveat: cancellation does not work.
13 *
14 * @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request
15 * waterfall β€” each one blocks rendering until it resolves, so the next doesn't even start fetching until then.
16 * Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they
17 * fetch in parallel.
18 * @param options - The {@link UseSuspenseQueryOptions} to use β€” the same options as `useQuery`, minus the ones listed above.
19 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
20 * be used.
21 * @returns The same object as `useQuery`, except that `data` is guaranteed to be defined, `isPlaceholderData`
22 * is missing, and `status` is either `success` or `error` (with the derived flags set accordingly).
23 *
24 * @example
25 * The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is
26 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
27 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
28 * ```tsx
29 * import { Suspense } from 'react'
30 * import { ErrorBoundary } from 'react-error-boundary'
31 * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query'
32 *
33 * function Posts() {
34 * // `data` is guaranteed to be defined here β€” no `isPending` check needed.
35 * const { data, isFetching } = useSuspenseQuery({
36 * queryKey: ['posts'],
37 * queryFn: fetchPosts,
38 * })
39 *
40 * return (
41 * <div>
42 * <h1>Posts {isFetching ? '(refreshing...)' : null}</h1>
43 * <ul>
44 * {data.map((post) => (
45 * <li key={post.id}>{post.title}</li>
46 * ))}
47 * </ul>
48 * </div>
49 * )
50 * }
51 *
52 * function App() {
53 * return (
54 * <QueryErrorResetBoundary>
55 * {({ reset }) => (
56 * <ErrorBoundary
57 * onReset={reset}
58 * fallbackRender={({ resetErrorBoundary }) => (
59 * <div>
60 * There was an error!
61 * <button onClick={() => resetErrorBoundary()}>Try again</button>
62 * </div>
63 * )}
64 * >
65 * <Suspense fallback={<h1>Loading posts...</h1>}>
66 * <Posts />
67 * </Suspense>
68 * </ErrorBoundary>
69 * )}
70 * </QueryErrorResetBoundary>
71 * )
72 * }
73 * ```
74 */
75export function useSuspenseQuery<
76 TQueryFnData = unknown,
77 TError = DefaultError,
78 TData = TQueryFnData,
79 TQueryKey extends QueryKey = QueryKey,
80>(
81 options: UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
82 queryClient?: QueryClient,
83): UseSuspenseQueryResult<TData, TError> {
84 if (process.env.NODE_ENV !== 'production') {
85 if ((options.queryFn as any) === skipToken) {
86 console.error('skipToken is not allowed for useSuspenseQuery')
87 }
88 }
89​
90 return useBaseQuery(
91 {
92 ...options,
93 enabled: true,
94 suspense: true,
95 throwOnError: defaultThrowOnError,
96 placeholderData: undefined,
97 },
98 QueryObserver,
99 queryClient,
100 ) as UseSuspenseQueryResult<TData, TError>