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