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