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

useQueries.ts

440 lines16.4 KB

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