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

useQueries.ts

440 lines15.9 KB

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