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

useSuspenseQuery.ts

121 lines4.0 KB

1import { QueryObserver, skipToken } from '@tanstack/query-core'
2import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
3​
4import { defaultThrowOnError } from './suspense'
5import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
6import { useBaseQuery } from './useBaseQuery'
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 *
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 'preact/compat'
30 * import { useErrorBoundary } from 'preact/hooks'
31 * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/preact-query'
32 * import type { ComponentChildren } from 'preact'
33 *
34 * function Posts() {
35 * // `data` is guaranteed to be defined here β€” no `isPending` check needed.
36 * const { data, isFetching } = useSuspenseQuery({
37 * queryKey: ['posts'],
38 * queryFn: fetchPosts,
39 * })
40 *
41 * return (
42 * <div>
43 * <h1>Posts {isFetching ? '(refreshing...)' : null}</h1>
44 * <ul>
45 * {data.map((post) => (
46 * <li key={post.id}>{post.title}</li>
47 * ))}
48 * </ul>
49 * </div>
50 * )
51 * }
52 *
53 * function App() {
54 * return (
55 * <QueryErrorResetBoundary>
56 * {({ reset }) => (
57 * <ErrorBoundary
58 * onReset={reset}
59 * fallbackRender={({ resetErrorBoundary }) => (
60 * <div>
61 * There was an error!
62 * <button onClick={() => resetErrorBoundary()}>Try again</button>
63 * </div>
64 * )}
65 * >
66 * <Suspense fallback={<h1>Loading posts...</h1>}>
67 * <Posts />
68 * </Suspense>
69 * </ErrorBoundary>
70 * )}
71 * </QueryErrorResetBoundary>
72 * )
73 * }
74 *
75 * function ErrorBoundary({
76 * children,
77 * onReset,
78 * fallbackRender,
79 * }: {
80 * children: ComponentChildren
81 * onReset: () => void
82 * fallbackRender: (props: {
83 * error: Error
84 * resetErrorBoundary: () => void
85 * }) => ComponentChildren
86 * }) {
87 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
88 *
89 * if (error) return fallbackRender({ error, resetErrorBoundary })
90 *
91 * return children
92 * }
93 * ```
94 */
95export function useSuspenseQuery<
96 TQueryFnData = unknown,
97 TError = DefaultError,
98 TData = TQueryFnData,
99 TQueryKey extends QueryKey = QueryKey,
100>(
101 options: UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
102 queryClient?: QueryClient,
103): UseSuspenseQueryResult<TData, TError> {
104 if (process.env.NODE_ENV !== 'production') {
105 if ((options.queryFn as any) === skipToken) {
106 console.error('skipToken is not allowed for useSuspenseQuery')
107 }
108 }
109​
110 return useBaseQuery(
111 {
112 ...options,
113 enabled: true,
114 suspense: true,
115 throwOnError: defaultThrowOnError,
116 placeholderData: undefined,
117 },
118 QueryObserver,
119 queryClient,
120 ) as UseSuspenseQueryResult<TData, TError>