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

useSuspenseQueries.ts

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