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