Open History to see the last commit
1import { QueryObserver, skipToken } from '@tanstack/query-core'
2import { defaultThrowOnError } from './suspense'
3import { useBaseQuery } from './useBaseQuery'
4import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
5β
6import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
7β
8/**
9 * The options for `useSuspenseQuery` are the same as for `useQuery`, except for
10 * `throwOnError`, `enabled`, and `placeholderData`.
11 *
12 * Caveat: cancellation does not work.
13 *
14 * @remarks
15 * Multiple `useSuspenseQuery` calls in the same component suspend serially,
16 * causing a request waterfall β each one blocks rendering until it resolves,
17 * so the next doesn't even start fetching until then. Use
18 * {@link useSuspenseQueries} instead when you have more than one suspenseful
19 * query in a component, so they fetch in parallel.
20 * @example
21 * The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is
22 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
23 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
24 * ```tsx
25 * import { Suspense } from 'preact/compat'
26 * import { useErrorBoundary } from 'preact/hooks'
27 * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/preact-query'
28 * import type { ComponentChildren } from 'preact'
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 * function ErrorBoundary({
72 * children,
73 * onReset,
74 * fallbackRender,
75 * }: {
76 * children: ComponentChildren
77 * onReset: () => void
78 * fallbackRender: (props: {
79 * error: Error
80 * resetErrorBoundary: () => void
81 * }) => ComponentChildren
82 * }) {
83 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
84 *
85 * if (error) return fallbackRender({ error, resetErrorBoundary })
86 *
87 * return children
88 * }
89 * ```
90 *
91 * @param options - The {@link UseSuspenseQueryOptions} to use β the same
92 * options as `useQuery`, minus the ones listed above.
93 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
94 * one from the nearest context will be used.
95 * @returns The same object as `useQuery`, except that `data` is guaranteed to
96 * be defined, `isPlaceholderData` is missing, and `status` is either
97 * `success` or `error` (with the derived flags set accordingly).
98 */
99export function useSuspenseQuery<
100 TQueryFnData = unknown,
101 TError = DefaultError,
102 TData = TQueryFnData,
103 TQueryKey extends QueryKey = QueryKey,
104>(
105 options: UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
106 queryClient?: QueryClient,
107): UseSuspenseQueryResult<TData, TError> {
108 if (process.env.NODE_ENV !== 'production') {
109 if ((options.queryFn as any) === skipToken) {
110 console.error('skipToken is not allowed for useSuspenseQuery')
111 }
112 }
113β
114 return useBaseQuery(
115 {
116 ...options,
117 enabled: true,
118 suspense: true,
119 throwOnError: defaultThrowOnError,
120 placeholderData: undefined,
121 },
122 QueryObserver,
123 queryClient,
124 ) as UseSuspenseQueryResult<TData, TError>
125}