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

useSuspenseQueries.ts

624 lines21.9 KB

1import { skipToken } from '@tanstack/query-core'
2import { defaultThrowOnError } from './suspense'
3import { useQueries } from './useQueries'
4import type {
5 DefaultError,
6 QueryClient,
7 QueryFunction,
8 ThrowOnError,
9} from '@tanstack/query-core'
10​
11import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types'
12​
13// Avoid TS depth-limit error in case of large array literal
14type MAXIMUM_DEPTH = 20
15​
16// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
17type SkipTokenForUseQueries = symbol
18​
19type GetUseSuspenseQueryOptions<T> =
20 // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
21 T extends {
22 queryFnData: infer TQueryFnData
23 error?: infer TError
24 data: infer TData
25 }
26 ? UseSuspenseQueryOptions<TQueryFnData, TError, TData>
27 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
28 ? UseSuspenseQueryOptions<TQueryFnData, TError>
29 : T extends { data: infer TData; error?: infer TError }
30 ? UseSuspenseQueryOptions<unknown, TError, TData>
31 : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
32 T extends [infer TQueryFnData, infer TError, infer TData]
33 ? UseSuspenseQueryOptions<TQueryFnData, TError, TData>
34 : T extends [infer TQueryFnData, infer TError]
35 ? UseSuspenseQueryOptions<TQueryFnData, TError>
36 : T extends [infer TQueryFnData]
37 ? UseSuspenseQueryOptions<TQueryFnData>
38 : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
39 T extends {
40 queryFn?:
41 | QueryFunction<infer TQueryFnData, infer TQueryKey>
42 | SkipTokenForUseQueries
43 select?: (data: any) => infer TData
44 throwOnError?: ThrowOnError<any, infer TError, any, any>
45 }
46 ? UseSuspenseQueryOptions<
47 TQueryFnData,
48 TError,
49 TData,
50 TQueryKey
51 >
52 : T extends {
53 queryFn?:
54 | QueryFunction<infer TQueryFnData, infer TQueryKey>
55 | SkipTokenForUseQueries
56 throwOnError?: ThrowOnError<any, infer TError, any, any>
57 }
58 ? UseSuspenseQueryOptions<
59 TQueryFnData,
60 TError,
61 TQueryFnData,
62 TQueryKey
63 >
64 : // Fallback
65 UseSuspenseQueryOptions
66​
67type GetUseSuspenseQueryResult<T> =
68 // Part 1: responsible for mapping explicit type parameter to function result, if object
69 T extends { queryFnData: any; error?: infer TError; data: infer TData }
70 ? UseSuspenseQueryResult<TData, TError>
71 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
72 ? UseSuspenseQueryResult<TQueryFnData, TError>
73 : T extends { data: infer TData; error?: infer TError }
74 ? UseSuspenseQueryResult<TData, TError>
75 : // Part 2: responsible for mapping explicit type parameter to function result, if tuple
76 T extends [any, infer TError, infer TData]
77 ? UseSuspenseQueryResult<TData, TError>
78 : T extends [infer TQueryFnData, infer TError]
79 ? UseSuspenseQueryResult<TQueryFnData, TError>
80 : T extends [infer TQueryFnData]
81 ? UseSuspenseQueryResult<TQueryFnData>
82 : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
83 T extends {
84 queryFn?:
85 | QueryFunction<infer TQueryFnData, any>
86 | SkipTokenForUseQueries
87 select?: (data: any) => infer TData
88 throwOnError?: ThrowOnError<any, infer TError, any, any>
89 }
90 ? UseSuspenseQueryResult<
91 unknown extends TData ? TQueryFnData : TData,
92 unknown extends TError ? DefaultError : TError
93 >
94 : T extends {
95 queryFn?:
96 | QueryFunction<infer TQueryFnData, any>
97 | SkipTokenForUseQueries
98 throwOnError?: ThrowOnError<any, infer TError, any, any>
99 }
100 ? UseSuspenseQueryResult<
101 TQueryFnData,
102 unknown extends TError ? DefaultError : TError
103 >
104 : // Fallback
105 UseSuspenseQueryResult
106​
107/**
108 * The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every
109 * entry's `queryFn`/`select` are inferred individually, up to 20 elements — past that, a tuple falls back to
110 * a single homogeneous {@link UseSuspenseQueryOptions} type.
111 *
112 * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally
113 * matches a query options object is mapped per-element instead, still inferring each entry individually; any
114 * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to
115 * that same homogeneous options type too.
116 * @template T - The type of the `queries` array as written at the call site.
117 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
118 * to be set explicitly.
119 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
120 * meant to be set explicitly.
121 */
122export type SuspenseQueriesOptions<
123 T extends Array<any>,
124 TResults extends Array<any> = [],
125 TDepth extends ReadonlyArray<number> = [],
126> = TDepth['length'] extends MAXIMUM_DEPTH
127 ? Array<UseSuspenseQueryOptions>
128 : T extends []
129 ? []
130 : T extends [infer Head]
131 ? [...TResults, GetUseSuspenseQueryOptions<Head>]
132 : T extends [infer Head, ...infer Tails]
133 ? SuspenseQueriesOptions<
134 [...Tails],
135 [...TResults, GetUseSuspenseQueryOptions<Head>],
136 [...TDepth, 1]
137 >
138 : Array<unknown> extends T
139 ? T
140 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
141 // use this to infer the param types in the case of Array.map() argument
142 T extends Array<
143 UseSuspenseQueryOptions<
144 infer TQueryFnData,
145 infer TError,
146 infer TData,
147 infer TQueryKey
148 >
149 >
150 ? Array<
151 UseSuspenseQueryOptions<TQueryFnData, TError, TData, TQueryKey>
152 >
153 : // Fallback
154 Array<UseSuspenseQueryOptions>
155​
156/**
157 * The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors
158 * {@link SuspenseQueriesOptions}: each tuple element's result type is inferred individually, up to 20 elements.
159 * A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20
160 * elements does this fall back to a single homogeneous {@link UseSuspenseQueryResult} type.
161 * @template T - The type of the `queries` array, as inferred by {@link SuspenseQueriesOptions}.
162 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
163 * to be set explicitly.
164 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
165 * meant to be set explicitly.
166 */
167export type SuspenseQueriesResults<
168 T extends Array<any>,
169 TResults extends Array<any> = [],
170 TDepth extends ReadonlyArray<number> = [],
171> = TDepth['length'] extends MAXIMUM_DEPTH
172 ? Array<UseSuspenseQueryResult>
173 : T extends []
174 ? []
175 : T extends [infer Head]
176 ? [...TResults, GetUseSuspenseQueryResult<Head>]
177 : T extends [infer Head, ...infer Tails]
178 ? SuspenseQueriesResults<
179 [...Tails],
180 [...TResults, GetUseSuspenseQueryResult<Head>],
181 [...TDepth, 1]
182 >
183 : { [K in keyof T]: GetUseSuspenseQueryResult<T[K]> }
184​
185/**
186 * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
187 * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
188 * @param options - The `queries` array to run in Suspense, and an optional `combine` function.
189 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
190 * will be used.
191 * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
192 * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
193 * flags set accordingly).
194 *
195 * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
196 * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
197 * this, make sure to set a high enough `staleTime`. Cancellation does not work.
198 * @example
199 * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
200 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
201 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
202 * ```tsx
203 * import { Suspense } from 'preact/compat'
204 * import { useErrorBoundary } from 'preact/hooks'
205 * import {
206 * QueryErrorResetBoundary,
207 * useSuspenseQueries,
208 * } from '@tanstack/preact-query'
209 * import type { ComponentChildren } from 'preact'
210 *
211 * function Posts({ ids }: { ids: Array<number> }) {
212 * // Every result is guaranteed to be defined — no per-query `isPending` check needed.
213 * const postQueries = useSuspenseQueries({
214 * queries: ids.map((id) => ({
215 * queryKey: ['post', id],
216 * queryFn: () => fetchPost(id),
217 * })),
218 * })
219 *
220 * return (
221 * <ul>
222 * {postQueries.map((query) => (
223 * <li key={query.data.id}>{query.data.title}</li>
224 * ))}
225 * </ul>
226 * )
227 * }
228 *
229 * function App() {
230 * return (
231 * <QueryErrorResetBoundary>
232 * {({ reset }) => (
233 * <ErrorBoundary
234 * onReset={reset}
235 * fallbackRender={({ resetErrorBoundary }) => (
236 * <div>
237 * There was an error!
238 * <button onClick={() => resetErrorBoundary()}>Try again</button>
239 * </div>
240 * )}
241 * >
242 * <Suspense fallback={<h1>Loading posts...</h1>}>
243 * <Posts ids={[1, 2, 3]} />
244 * </Suspense>
245 * </ErrorBoundary>
246 * )}
247 * </QueryErrorResetBoundary>
248 * )
249 * }
250 *
251 * function ErrorBoundary({
252 * children,
253 * onReset,
254 * fallbackRender,
255 * }: {
256 * children: ComponentChildren
257 * onReset: () => void
258 * fallbackRender: (props: {
259 * error: Error
260 * resetErrorBoundary: () => void
261 * }) => ComponentChildren
262 * }) {
263 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
264 *
265 * if (error) return fallbackRender({ error, resetErrorBoundary })
266 *
267 * return children
268 * }
269 * ```
270 * @example
271 * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
272 * they fetch in parallel rather than suspending one after another:
273 * ```tsx
274 * import { Suspense } from 'preact/compat'
275 * import { useErrorBoundary } from 'preact/hooks'
276 * import {
277 * QueryErrorResetBoundary,
278 * useSuspenseQueries,
279 * } from '@tanstack/preact-query'
280 * import type { ComponentChildren } from 'preact'
281 *
282 * function Dashboard() {
283 * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
284 * queries: [
285 * { queryKey: ['users'], queryFn: fetchUsers },
286 * { queryKey: ['teams'], queryFn: fetchTeams },
287 * { queryKey: ['projects'], queryFn: fetchProjects },
288 * ],
289 * })
290 *
291 * return (
292 * <div>
293 * <UserList users={usersQuery.data} />
294 * <TeamList teams={teamsQuery.data} />
295 * <ProjectList projects={projectsQuery.data} />
296 * </div>
297 * )
298 * }
299 *
300 * function App() {
301 * return (
302 * <QueryErrorResetBoundary>
303 * {({ reset }) => (
304 * <ErrorBoundary
305 * onReset={reset}
306 * fallbackRender={({ resetErrorBoundary }) => (
307 * <div>
308 * There was an error!
309 * <button onClick={() => resetErrorBoundary()}>Try again</button>
310 * </div>
311 * )}
312 * >
313 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
314 * <Dashboard />
315 * </Suspense>
316 * </ErrorBoundary>
317 * )}
318 * </QueryErrorResetBoundary>
319 * )
320 * }
321 *
322 * function ErrorBoundary({
323 * children,
324 * onReset,
325 * fallbackRender,
326 * }: {
327 * children: ComponentChildren
328 * onReset: () => void
329 * fallbackRender: (props: {
330 * error: Error
331 * resetErrorBoundary: () => void
332 * }) => ComponentChildren
333 * }) {
334 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
335 *
336 * if (error) return fallbackRender({ error, resetErrorBoundary })
337 *
338 * return children
339 * }
340 * ```
341 * @example
342 * `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes,
343 * not on every individual query update. This overload is the only one that accepts `combine`:
344 * ```tsx
345 * import { Suspense } from 'preact/compat'
346 * import { useErrorBoundary } from 'preact/hooks'
347 * import {
348 * QueryErrorResetBoundary,
349 * useSuspenseQueries,
350 * } from '@tanstack/preact-query'
351 * import type { ComponentChildren } from 'preact'
352 *
353 * function Refresh() {
354 * const anyFetching = useSuspenseQueries({
355 * queries: [
356 * { queryKey: ['users'], queryFn: fetchUsers },
357 * { queryKey: ['teams'], queryFn: fetchTeams },
358 * ],
359 * combine: (results) => results.some((result) => result.isFetching),
360 * })
361 *
362 * return anyFetching ? <span>Refreshing…</span> : null
363 * }
364 *
365 * function App() {
366 * return (
367 * <QueryErrorResetBoundary>
368 * {({ reset }) => (
369 * <ErrorBoundary
370 * onReset={reset}
371 * fallbackRender={({ resetErrorBoundary }) => (
372 * <div>
373 * There was an error!
374 * <button onClick={() => resetErrorBoundary()}>Try again</button>
375 * </div>
376 * )}
377 * >
378 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
379 * <Refresh />
380 * </Suspense>
381 * </ErrorBoundary>
382 * )}
383 * </QueryErrorResetBoundary>
384 * )
385 * }
386 *
387 * function ErrorBoundary({
388 * children,
389 * onReset,
390 * fallbackRender,
391 * }: {
392 * children: ComponentChildren
393 * onReset: () => void
394 * fallbackRender: (props: {
395 * error: Error
396 * resetErrorBoundary: () => void
397 * }) => ComponentChildren
398 * }) {
399 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
400 *
401 * if (error) return fallbackRender({ error, resetErrorBoundary })
402 *
403 * return children
404 * }
405 * ```
406 */
407export function useSuspenseQueries<
408 T extends Array<any>,
409 TCombinedResult = SuspenseQueriesResults<T>,
410>(
411 options: {
412 /**
413 * An array with query option objects identical to `useSuspenseQuery`.
414 */
415 queries:
416 | readonly [...SuspenseQueriesOptions<T>]
417 | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions<T[K]> }]
418 /**
419 * Use this to combine the results of the queries into a single value. The result will be structurally
420 * shared to be as referentially stable as possible.
421 */
422 combine?: (result: SuspenseQueriesResults<T>) => TCombinedResult
423 },
424 queryClient?: QueryClient,
425): TCombinedResult
426​
427/**
428 * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed`
429 * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`.
430 * @param options - The `queries` array to run in Suspense, and an optional `combine` function.
431 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
432 * will be used.
433 * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be
434 * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived
435 * flags set accordingly).
436 *
437 * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone
438 * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid
439 * this, make sure to set a high enough `staleTime`. Cancellation does not work.
440 * @example
441 * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is
442 * required around `<Suspense>`. A failed background refetch instead continues to render the cached data.
443 * Use {@link QueryErrorResetBoundary} to let the user retry after such an error:
444 * ```tsx
445 * import { Suspense } from 'preact/compat'
446 * import { useErrorBoundary } from 'preact/hooks'
447 * import {
448 * QueryErrorResetBoundary,
449 * useSuspenseQueries,
450 * } from '@tanstack/preact-query'
451 * import type { ComponentChildren } from 'preact'
452 *
453 * function Posts({ ids }: { ids: Array<number> }) {
454 * // Every result is guaranteed to be defined — no per-query `isPending` check needed.
455 * const postQueries = useSuspenseQueries({
456 * queries: ids.map((id) => ({
457 * queryKey: ['post', id],
458 * queryFn: () => fetchPost(id),
459 * })),
460 * })
461 *
462 * return (
463 * <ul>
464 * {postQueries.map((query) => (
465 * <li key={query.data.id}>{query.data.title}</li>
466 * ))}
467 * </ul>
468 * )
469 * }
470 *
471 * function App() {
472 * return (
473 * <QueryErrorResetBoundary>
474 * {({ reset }) => (
475 * <ErrorBoundary
476 * onReset={reset}
477 * fallbackRender={({ resetErrorBoundary }) => (
478 * <div>
479 * There was an error!
480 * <button onClick={() => resetErrorBoundary()}>Try again</button>
481 * </div>
482 * )}
483 * >
484 * <Suspense fallback={<h1>Loading posts...</h1>}>
485 * <Posts ids={[1, 2, 3]} />
486 * </Suspense>
487 * </ErrorBoundary>
488 * )}
489 * </QueryErrorResetBoundary>
490 * )
491 * }
492 *
493 * function ErrorBoundary({
494 * children,
495 * onReset,
496 * fallbackRender,
497 * }: {
498 * children: ComponentChildren
499 * onReset: () => void
500 * fallbackRender: (props: {
501 * error: Error
502 * resetErrorBoundary: () => void
503 * }) => ComponentChildren
504 * }) {
505 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
506 *
507 * if (error) return fallbackRender({ error, resetErrorBoundary })
508 *
509 * return children
510 * }
511 * ```
512 * @example
513 * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so
514 * they fetch in parallel rather than suspending one after another:
515 * ```tsx
516 * import { Suspense } from 'preact/compat'
517 * import { useErrorBoundary } from 'preact/hooks'
518 * import {
519 * QueryErrorResetBoundary,
520 * useSuspenseQueries,
521 * } from '@tanstack/preact-query'
522 * import type { ComponentChildren } from 'preact'
523 *
524 * function Dashboard() {
525 * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({
526 * queries: [
527 * { queryKey: ['users'], queryFn: fetchUsers },
528 * { queryKey: ['teams'], queryFn: fetchTeams },
529 * { queryKey: ['projects'], queryFn: fetchProjects },
530 * ],
531 * })
532 *
533 * return (
534 * <div>
535 * <UserList users={usersQuery.data} />
536 * <TeamList teams={teamsQuery.data} />
537 * <ProjectList projects={projectsQuery.data} />
538 * </div>
539 * )
540 * }
541 *
542 * function App() {
543 * return (
544 * <QueryErrorResetBoundary>
545 * {({ reset }) => (
546 * <ErrorBoundary
547 * onReset={reset}
548 * fallbackRender={({ resetErrorBoundary }) => (
549 * <div>
550 * There was an error!
551 * <button onClick={() => resetErrorBoundary()}>Try again</button>
552 * </div>
553 * )}
554 * >
555 * <Suspense fallback={<h1>Loading dashboard...</h1>}>
556 * <Dashboard />
557 * </Suspense>
558 * </ErrorBoundary>
559 * )}
560 * </QueryErrorResetBoundary>
561 * )
562 * }
563 *
564 * function ErrorBoundary({
565 * children,
566 * onReset,
567 * fallbackRender,
568 * }: {
569 * children: ComponentChildren
570 * onReset: () => void
571 * fallbackRender: (props: {
572 * error: Error
573 * resetErrorBoundary: () => void
574 * }) => ComponentChildren
575 * }) {
576 * const [error, resetErrorBoundary] = useErrorBoundary(() => onReset())
577 *
578 * if (error) return fallbackRender({ error, resetErrorBoundary })
579 *
580 * return children
581 * }
582 * ```
583 */
584export function useSuspenseQueries<
585 T extends Array<any>,
586 TCombinedResult = SuspenseQueriesResults<T>,
587>(
588 options: {
589 /**
590 * An array with query option objects identical to `useSuspenseQuery`.
591 */
592 queries: readonly [...SuspenseQueriesOptions<T>]
593 /**
594 * Use this to combine the results of the queries into a single value. The result will be structurally
595 * shared to be as referentially stable as possible.
596 */
597 combine?: (result: SuspenseQueriesResults<T>) => TCombinedResult
598 },
599 queryClient?: QueryClient,
600): TCombinedResult
601​
602export function useSuspenseQueries(options: any, queryClient?: QueryClient) {
603 return useQueries(
604 {
605 ...options,
606 queries: options.queries.map((query: any) => {
607 if (process.env.NODE_ENV !== 'production') {
608 if (query.queryFn === skipToken) {
609 console.error('skipToken is not allowed for useSuspenseQueries')
610 }
611 }
612​
613 return {
614 ...query,
615 suspense: true,
616 throwOnError: defaultThrowOnError,
617 enabled: true,
618 placeholderData: undefined,
619 }
620 }),
621 },
622 queryClient,
623 )