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