Open History to see the last commit
1import {
2 QueriesObserver,
3 QueryObserver,
4 noop,
5 notifyManager,
6} from '@tanstack/query-core'
7import { useCallback, useEffect, useMemo, useState } from 'preact/hooks'
8β
9import { useIsRestoring } from './IsRestoringProvider'
10import { useQueryClient } from './QueryClientProvider'
11import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
12import {
13 ensurePreventErrorBoundaryRetry,
14 getHasError,
15 useClearResetErrorBoundary,
16} from './errorBoundaryUtils'
17import {
18 ensureSuspenseTimers,
19 fetchOptimistic,
20 shouldSuspend,
21} from './suspense'
22import { useSyncExternalStore } from './utils'
23import type {
24 DefinedUseQueryResult,
25 UseQueryOptions,
26 UseQueryResult,
27} from './types'
28import type {
29 DefaultError,
30 OmitKeyof,
31 QueriesObserverOptions,
32 QueriesPlaceholderDataFunction,
33 QueryClient,
34 QueryFunction,
35 QueryKey,
36 QueryObserverOptions,
37 ThrowOnError,
38} from '@tanstack/query-core'
39β
40// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
41// `placeholderData` function always gets undefined passed
42type UseQueryOptionsForUseQueries<
43 TQueryFnData = unknown,
44 TError = DefaultError,
45 TData = TQueryFnData,
46 TQueryKey extends QueryKey = QueryKey,
47> = OmitKeyof<
48 UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
49 'placeholderData' | 'subscribed'
50> & {
51 placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>
52}
53β
54// Avoid TS depth-limit error in case of large array literal
55type MAXIMUM_DEPTH = 20
56β
57// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
58type SkipTokenForUseQueries = symbol
59β
60type GetUseQueryOptionsForUseQueries<T> =
61 // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
62 T extends {
63 queryFnData: infer TQueryFnData
64 error?: infer TError
65 data: infer TData
66 }
67 ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
68 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
69 ? UseQueryOptionsForUseQueries<TQueryFnData, TError>
70 : T extends { data: infer TData; error?: infer TError }
71 ? UseQueryOptionsForUseQueries<unknown, TError, TData>
72 : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
73 T extends [infer TQueryFnData, infer TError, infer TData]
74 ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
75 : T extends [infer TQueryFnData, infer TError]
76 ? UseQueryOptionsForUseQueries<TQueryFnData, TError>
77 : T extends [infer TQueryFnData]
78 ? UseQueryOptionsForUseQueries<TQueryFnData>
79 : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
80 T extends {
81 queryFn?:
82 | QueryFunction<infer TQueryFnData, infer TQueryKey>
83 | SkipTokenForUseQueries
84 select?: (data: any) => infer TData
85 throwOnError?: ThrowOnError<any, infer TError, any, any>
86 }
87 ? UseQueryOptionsForUseQueries<
88 TQueryFnData,
89 unknown extends TError ? DefaultError : TError,
90 unknown extends TData ? TQueryFnData : TData,
91 TQueryKey
92 >
93 : // Fallback
94 UseQueryOptionsForUseQueries
95β
96// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult
97type GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {
98 initialData?: infer TInitialData
99}
100 ? unknown extends TInitialData
101 ? UseQueryResult<TData, TError>
102 : TInitialData extends TData
103 ? DefinedUseQueryResult<TData, TError>
104 : TInitialData extends () => infer TInitialDataResult
105 ? unknown extends TInitialDataResult
106 ? UseQueryResult<TData, TError>
107 : TInitialDataResult extends TData
108 ? DefinedUseQueryResult<TData, TError>
109 : UseQueryResult<TData, TError>
110 : UseQueryResult<TData, TError>
111 : UseQueryResult<TData, TError>
112β
113type GetUseQueryResult<T> =
114 // Part 1: responsible for mapping explicit type parameter to function result, if object
115 T extends { queryFnData: any; error?: infer TError; data: infer TData }
116 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
117 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
118 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
119 : T extends { data: infer TData; error?: infer TError }
120 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
121 : // Part 2: responsible for mapping explicit type parameter to function result, if tuple
122 T extends [any, infer TError, infer TData]
123 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
124 : T extends [infer TQueryFnData, infer TError]
125 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
126 : T extends [infer TQueryFnData]
127 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>
128 : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
129 T extends {
130 queryFn?:
131 | QueryFunction<infer TQueryFnData, any>
132 | SkipTokenForUseQueries
133 select?: (data: any) => infer TData
134 throwOnError?: ThrowOnError<any, infer TError, any, any>
135 }
136 ? GetDefinedOrUndefinedQueryResult<
137 T,
138 unknown extends TData ? TQueryFnData : TData,
139 unknown extends TError ? DefaultError : TError
140 >
141 : // Fallback
142 UseQueryResult
143β
144/**
145 * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple
146 * element so every entry's `queryFn`/`select`/`throwOnError` are inferred
147 * individually, up to 20 elements β past that, a tuple falls back to a single
148 * homogeneous options type.
149 *
150 * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose
151 * element type structurally matches a query options object is mapped
152 * per-element instead, still inferring each entry individually; any other
153 * non-tuple array β one whose element type doesn't match the expected options
154 * shape β falls back to that same homogeneous options type too.
155 *
156 * @template T - The type of the `queries` array as written at the call site.
157 * @template TResults - The internal accumulator that this type builds during
158 * recursion. It is not meant to be set explicitly.
159 * @template TDepth - The internal recursion-depth counter, checked against the
160 * 20-element limit. It is not meant to be set explicitly.
161 */
162export type QueriesOptions<
163 T extends Array<any>,
164 TResults extends Array<any> = [],
165 TDepth extends ReadonlyArray<number> = [],
166> = TDepth['length'] extends MAXIMUM_DEPTH
167 ? Array<UseQueryOptionsForUseQueries>
168 : T extends []
169 ? []
170 : T extends [infer Head]
171 ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]
172 : T extends [infer Head, ...infer Tails]
173 ? QueriesOptions<
174 [...Tails],
175 [...TResults, GetUseQueryOptionsForUseQueries<Head>],
176 [...TDepth, 1]
177 >
178 : ReadonlyArray<unknown> extends T
179 ? T
180 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
181 // use this to infer the param types in the case of Array.map() argument
182 T extends Array<
183 UseQueryOptionsForUseQueries<
184 infer TQueryFnData,
185 infer TError,
186 infer TData,
187 infer TQueryKey
188 >
189 >
190 ? Array<
191 UseQueryOptionsForUseQueries<
192 TQueryFnData,
193 TError,
194 TData,
195 TQueryKey
196 >
197 >
198 : // Fallback
199 Array<UseQueryOptionsForUseQueries>
200β
201/**
202 * The result type returned by `useQueries`, when no `combine` is provided.
203 * Mirrors {@link QueriesOptions}: each tuple element's result type is inferred
204 * individually, up to 20 elements. A non-tuple array is mapped per-element
205 * instead, still inferring each entry individually; only past 20 elements does
206 * this fall back to a single homogeneous {@link UseQueryResult} type.
207 *
208 * @template T - The type of the `queries` array, as inferred by
209 * {@link QueriesOptions}.
210 * @template TResults - The internal accumulator that this type builds during
211 * recursion. It is not meant to be set explicitly.
212 * @template TDepth - The internal recursion-depth counter, checked against the
213 * 20-element limit. It is not meant to be set explicitly.
214 */
215export type QueriesResults<
216 T extends Array<any>,
217 TResults extends Array<any> = [],
218 TDepth extends ReadonlyArray<number> = [],
219> = TDepth['length'] extends MAXIMUM_DEPTH
220 ? Array<UseQueryResult>
221 : T extends []
222 ? []
223 : T extends [infer Head]
224 ? [...TResults, GetUseQueryResult<Head>]
225 : T extends [infer Head, ...infer Tails]
226 ? QueriesResults<
227 [...Tails],
228 [...TResults, GetUseQueryResult<Head>],
229 [...TDepth, 1]
230 >
231 : { [K in keyof T]: GetUseQueryResult<T[K]> }
232β
233/**
234 * The `useQueries` hook can be used to fetch a variable number of queries.
235 *
236 * The `queries` key accepts an array with query option objects mostly identical
237 * to `useQuery` β see the `queries` parameter below for the differences. A
238 * custom `QueryClient` is supplied once, as `useQueries`' own top-level second
239 * argument, rather than per query.
240 *
241 * Having the same query key more than once in the array of query objects may
242 * cause some data to be shared between queries. To avoid this, consider
243 * de-duplicating the queries and map the results back to the desired
244 * structure.
245 *
246 * The `combine` option can be used to combine the results of the queries into a
247 * single value. The result will be structurally shared to be as referentially
248 * stable as possible.
249 *
250 * @example
251 * ;```tsx
252 * import { useQueries } from '@tanstack/preact-query'
253 *
254 * function Posts({ ids }: { ids: Array<number> }) {
255 * const postQueries = useQueries({
256 * queries: ids.map((id) => ({
257 * queryKey: ['post', id],
258 * queryFn: () => fetchPost(id),
259 * staleTime: Infinity,
260 * })),
261 * })
262 *
263 * return (
264 * <ul>
265 * {postQueries.map((query, index) => {
266 * if (query.isPending) return <li key={ids[index]}>Loading...</li>
267 * if (query.isError)
268 * return <li key={ids[index]}>Error: {query.error.message}</li>
269 * return <li key={ids[index]}>{query.data.title}</li>
270 * })}
271 * </ul>
272 * )
273 * }
274 * ```
275 *
276 * @example
277 * Combining results into a single value:
278 * ```tsx
279 * import { useQueries } from '@tanstack/preact-query'
280 *
281 * function Posts({ ids }: { ids: Array<number> }) {
282 * const { data, isPending, isError } = useQueries({
283 * queries: ids.map((id) => ({
284 * queryKey: ['post', id],
285 * queryFn: () => fetchPost(id),
286 * })),
287 * combine: (postQueries) => {
288 * return {
289 * data: postQueries.map((query) => query.data),
290 * isPending: postQueries.some((query) => query.isPending),
291 * isError: postQueries.some((query) => query.isError),
292 * }
293 * },
294 * })
295 *
296 * if (isPending) return 'Loading...'
297 * if (isError) return 'Error loading posts'
298 *
299 * return (
300 * <ul>
301 * {data.map((post) => (
302 * <li key={post?.id}>{post?.title}</li>
303 * ))}
304 * </ul>
305 * )
306 * }
307 * ```
308 *
309 * @param options - The `queries` array to run, and the optional `combine` and
310 * `subscribed` options.
311 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise,
312 * the one from the nearest context will be used.
313 * @returns The combined result. Without `combine`, this is an array with all
314 * the query results, in the same order as the input. When `combine` is
315 * provided, this is the value returned by `combine` instead.
316 * @throws {Error} The error of the first query that should be thrown to the
317 * nearest error boundary (see `throwOnError`). While suspending, it throws a
318 * promise instead.
319 */
320export function useQueries<
321 T extends Array<any>,
322 TCombinedResult = QueriesResults<T>,
323>(
324 {
325 queries,
326 ...options
327 }: {
328 /**
329 * An array with query option objects, mostly identical to `useQuery` β
330 * except that `queryClient` and `subscribed` aren't accepted per-query
331 * (`subscribed` is a top-level option here instead), and `placeholderData`
332 * accepts a {@link QueriesPlaceholderDataFunction}, which is called with
333 * `previousData` and `previousQuery` always `undefined`, rather than
334 * `useQuery`'s placeholder function.
335 */
336 queries:
337 | readonly [...QueriesOptions<T>]
338 | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]
339 /**
340 * Use this to combine the results of the queries into a single value. The
341 * result will be structurally shared to be as referentially stable as
342 * possible.
343 */
344 combine?: (result: QueriesResults<T>) => TCombinedResult
345 /**
346 * Set this to `false` to unsubscribe this observer from updates to the
347 * query cache.
348 *
349 * @defaultValue true
350 */
351 subscribed?: boolean
352 },
353 queryClient?: QueryClient,
354): TCombinedResult {
355 const client = useQueryClient(queryClient)
356 const isRestoring = useIsRestoring()
357 const errorResetBoundary = useQueryErrorResetBoundary()
358 const subscribed = options.subscribed !== false
359β
360 const defaultedQueries = useMemo(
361 () =>
362 queries.map((opts) => {
363 const defaultedOptions = client.defaultQueryOptions(
364 opts as QueryObserverOptions,
365 )
366β
367 // Make sure the results are already in fetching state before subscribing or updating options
368 defaultedOptions._optimisticResults = isRestoring
369 ? 'isRestoring'
370 : subscribed
371 ? 'optimistic'
372 : undefined
373β
374 return defaultedOptions
375 }),
376 [queries, client, isRestoring, subscribed],
377 )
378β
379 defaultedQueries.forEach((queryOptions) => {
380 ensureSuspenseTimers(queryOptions)
381 const query = client.getQueryCache().get(queryOptions.queryHash)
382 ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)
383 })
384β
385 useClearResetErrorBoundary(errorResetBoundary)
386β
387 const [observer] = useState(
388 () =>
389 new QueriesObserver<TCombinedResult>(
390 client,
391 defaultedQueries,
392 options as QueriesObserverOptions<TCombinedResult>,
393 ),
394 )
395β
396 // note: this must be called before useSyncExternalStore
397 const [optimisticResult, getCombinedResult, trackResult] =
398 observer.getOptimisticResult(
399 defaultedQueries,
400 (options as QueriesObserverOptions<TCombinedResult>).combine,
401 )
402β
403 const shouldSubscribe = !isRestoring && subscribed
404 useSyncExternalStore(
405 useCallback(
406 (onStoreChange) =>
407 shouldSubscribe
408 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
409 : noop,
410 [observer, shouldSubscribe],
411 ),
412 () => observer.getCurrentResult(),
413 )
414β
415 useEffect(() => {
416 observer.setQueries(
417 defaultedQueries,
418 options as QueriesObserverOptions<TCombinedResult>,
419 )
420 }, [defaultedQueries, options, observer])
421β
422 const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>
423 shouldSuspend(defaultedQueries[index], result),
424 )
425β
426 const suspensePromises = shouldAtLeastOneSuspend
427 ? optimisticResult.flatMap((result, index) => {
428 const opts = defaultedQueries[index]
429β
430 if (opts && shouldSuspend(opts, result)) {
431 const queryObserver = new QueryObserver(client, opts)
432 return fetchOptimistic(opts, queryObserver, errorResetBoundary)
433 }
434 return []
435 })
436 : []
437β
438 if (suspensePromises.length > 0) {
439 throw Promise.all(suspensePromises)
440 }
441 const firstSingleResultWhichShouldThrow = optimisticResult.find(
442 (result, index) => {
443 const query = defaultedQueries[index]
444 return (
445 query &&
446 getHasError({
447 result,
448 errorResetBoundary,
449 throwOnError: query.throwOnError,
450 query: client.getQueryCache().get(query.queryHash),
451 suspense: query.suspense,
452 })
453 )
454 },
455 )
456β
457 if (firstSingleResultWhichShouldThrow) {
458 throw firstSingleResultWhichShouldThrow.error
459 }
460β
461 return getCombinedResult(trackResult())
462}