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 element so every entry's
146 * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements β past that, a tuple falls
147 * back to a single homogeneous options type.
148 *
149 * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally
150 * matches a query options object is mapped per-element instead, still inferring each entry individually; any
151 * other non-tuple array β one whose element type doesn't match the expected options shape β falls back to
152 * that same homogeneous options type too.
153 * @template T - The type of the `queries` array as written at the call site.
154 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
155 * to be set explicitly.
156 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
157 * meant to be set explicitly.
158 */
159export type QueriesOptions<
160 T extends Array<any>,
161 TResults extends Array<any> = [],
162 TDepth extends ReadonlyArray<number> = [],
163> = TDepth['length'] extends MAXIMUM_DEPTH
164 ? Array<UseQueryOptionsForUseQueries>
165 : T extends []
166 ? []
167 : T extends [infer Head]
168 ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]
169 : T extends [infer Head, ...infer Tails]
170 ? QueriesOptions<
171 [...Tails],
172 [...TResults, GetUseQueryOptionsForUseQueries<Head>],
173 [...TDepth, 1]
174 >
175 : ReadonlyArray<unknown> extends T
176 ? T
177 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
178 // use this to infer the param types in the case of Array.map() argument
179 T extends Array<
180 UseQueryOptionsForUseQueries<
181 infer TQueryFnData,
182 infer TError,
183 infer TData,
184 infer TQueryKey
185 >
186 >
187 ? Array<
188 UseQueryOptionsForUseQueries<
189 TQueryFnData,
190 TError,
191 TData,
192 TQueryKey
193 >
194 >
195 : // Fallback
196 Array<UseQueryOptionsForUseQueries>
197β
198/**
199 * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each
200 * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped
201 * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a
202 * single homogeneous {@link UseQueryResult} type.
203 * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
204 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant
205 * to be set explicitly.
206 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
207 * meant to be set explicitly.
208 */
209export type QueriesResults<
210 T extends Array<any>,
211 TResults extends Array<any> = [],
212 TDepth extends ReadonlyArray<number> = [],
213> = TDepth['length'] extends MAXIMUM_DEPTH
214 ? Array<UseQueryResult>
215 : T extends []
216 ? []
217 : T extends [infer Head]
218 ? [...TResults, GetUseQueryResult<Head>]
219 : T extends [infer Head, ...infer Tails]
220 ? QueriesResults<
221 [...Tails],
222 [...TResults, GetUseQueryResult<Head>],
223 [...TDepth, 1]
224 >
225 : { [K in keyof T]: GetUseQueryResult<T[K]> }
226β
227/**
228 * The `useQueries` hook can be used to fetch a variable number of queries.
229 *
230 * The `queries` key accepts an array with query option objects mostly identical to `useQuery` β see the
231 * `queries` parameter below for the differences. A custom `QueryClient` is supplied once, as `useQueries`' own
232 * top-level second argument, rather than per query.
233 *
234 * Having the same query key more than once in the array of query objects may cause some data to be shared
235 * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
236 * structure.
237 *
238 * The `combine` option can be used to combine the results of the queries into a single value. The result will
239 * be structurally shared to be as referentially stable as possible.
240 * @param options - The `queries` array to run, and the optional `combine` and `subscribed` options.
241 * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
242 * will be used.
243 * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
244 * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
245 * @throws {Error} The error of the first query that should be thrown to the nearest error boundary (see
246 * `throwOnError`). While suspending, it throws a promise instead.
247 * @example
248 * ```tsx
249 * import { useQueries } from '@tanstack/preact-query'
250 *
251 * function Posts({ ids }: { ids: Array<number> }) {
252 * const postQueries = useQueries({
253 * queries: ids.map((id) => ({
254 * queryKey: ['post', id],
255 * queryFn: () => fetchPost(id),
256 * staleTime: Infinity,
257 * })),
258 * })
259 *
260 * return (
261 * <ul>
262 * {postQueries.map((query, index) => {
263 * if (query.isPending) return <li key={ids[index]}>Loading...</li>
264 * if (query.isError) return <li key={ids[index]}>Error: {query.error.message}</li>
265 * return <li key={ids[index]}>{query.data.title}</li>
266 * })}
267 * </ul>
268 * )
269 * }
270 * ```
271 * @example
272 * Combining results into a single value:
273 * ```tsx
274 * import { useQueries } from '@tanstack/preact-query'
275 *
276 * function Posts({ ids }: { ids: Array<number> }) {
277 * const { data, isPending, isError } = useQueries({
278 * queries: ids.map((id) => ({
279 * queryKey: ['post', id],
280 * queryFn: () => fetchPost(id),
281 * })),
282 * combine: (postQueries) => {
283 * return {
284 * data: postQueries.map((query) => query.data),
285 * isPending: postQueries.some((query) => query.isPending),
286 * isError: postQueries.some((query) => query.isError),
287 * }
288 * },
289 * })
290 *
291 * if (isPending) return 'Loading...'
292 * if (isError) return 'Error loading posts'
293 *
294 * return (
295 * <ul>
296 * {data.map((post) => (
297 * <li key={post?.id}>{post?.title}</li>
298 * ))}
299 * </ul>
300 * )
301 * }
302 * ```
303 */
304export function useQueries<
305 T extends Array<any>,
306 TCombinedResult = QueriesResults<T>,
307>(
308 {
309 queries,
310 ...options
311 }: {
312 /**
313 * An array with query option objects, mostly identical to `useQuery` β except that `queryClient` and
314 * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and
315 * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`
316 * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.
317 */
318 queries:
319 | readonly [...QueriesOptions<T>]
320 | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]
321 /**
322 * Use this to combine the results of the queries into a single value. The result will be structurally
323 * shared to be as referentially stable as possible.
324 */
325 combine?: (result: QueriesResults<T>) => TCombinedResult
326 /**
327 * Set this to `false` to unsubscribe this observer from updates to the query cache.
328 * @defaultValue true
329 */
330 subscribed?: boolean
331 },
332 queryClient?: QueryClient,
333): TCombinedResult {
334 const client = useQueryClient(queryClient)
335 const isRestoring = useIsRestoring()
336 const errorResetBoundary = useQueryErrorResetBoundary()
337 const subscribed = options.subscribed !== false
338β
339 const defaultedQueries = useMemo(
340 () =>
341 queries.map((opts) => {
342 const defaultedOptions = client.defaultQueryOptions(
343 opts as QueryObserverOptions,
344 )
345β
346 // Make sure the results are already in fetching state before subscribing or updating options
347 defaultedOptions._optimisticResults = isRestoring
348 ? 'isRestoring'
349 : subscribed
350 ? 'optimistic'
351 : undefined
352β
353 return defaultedOptions
354 }),
355 [queries, client, isRestoring, subscribed],
356 )
357β
358 defaultedQueries.forEach((queryOptions) => {
359 ensureSuspenseTimers(queryOptions)
360 const query = client.getQueryCache().get(queryOptions.queryHash)
361 ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)
362 })
363β
364 useClearResetErrorBoundary(errorResetBoundary)
365β
366 const [observer] = useState(
367 () =>
368 new QueriesObserver<TCombinedResult>(
369 client,
370 defaultedQueries,
371 options as QueriesObserverOptions<TCombinedResult>,
372 ),
373 )
374β
375 // note: this must be called before useSyncExternalStore
376 const [optimisticResult, getCombinedResult, trackResult] =
377 observer.getOptimisticResult(
378 defaultedQueries,
379 (options as QueriesObserverOptions<TCombinedResult>).combine,
380 )
381β
382 useEffect(() => {
383 observer.setQueries(
384 defaultedQueries,
385 options as QueriesObserverOptions<TCombinedResult>,
386 )
387 }, [defaultedQueries, options, observer])
388β
389 const shouldSubscribe = !isRestoring && subscribed
390 useSyncExternalStore(
391 useCallback(
392 (onStoreChange) =>
393 shouldSubscribe
394 ? observer.subscribe(notifyManager.batchCalls(onStoreChange))
395 : noop,
396 [observer, shouldSubscribe],
397 ),
398 () => observer.getCurrentResult(),
399 )
400β
401 const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>
402 shouldSuspend(defaultedQueries[index], result),
403 )
404β
405 const suspensePromises = shouldAtLeastOneSuspend
406 ? optimisticResult.flatMap((result, index) => {
407 const opts = defaultedQueries[index]
408β
409 if (opts && shouldSuspend(opts, result)) {
410 const queryObserver = new QueryObserver(client, opts)
411 return fetchOptimistic(opts, queryObserver, errorResetBoundary)
412 }
413 return []
414 })
415 : []
416β
417 if (suspensePromises.length > 0) {
418 throw Promise.all(suspensePromises)
419 }
420 const firstSingleResultWhichShouldThrow = optimisticResult.find(
421 (result, index) => {
422 const query = defaultedQueries[index]
423 return (
424 query &&
425 getHasError({
426 result,
427 errorResetBoundary,
428 throwOnError: query.throwOnError,
429 query: client.getQueryCache().get(query.queryHash),
430 suspense: query.suspense,
431 })
432 )
433 },
434 )
435β
436 if (firstSingleResultWhichShouldThrow) {
437 throw firstSingleResultWhichShouldThrow.error
438 }
439β
440 return getCombinedResult(trackResult())
441}