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

useQueries.ts

458 lines15.2 KB

1import { QueriesObserver, noop } from '@tanstack/query-core'
2import { createStore, unwrap } from 'solid-js/store'
3import {
4 batch,
5 createComputed,
6 createMemo,
7 createRenderEffect,
8 createResource,
9 createSignal,
10 mergeProps,
11 on,
12 onCleanup,
13 onMount,
14} from 'solid-js'
15import { useQueryClientResolver } from './QueryClientProvider'
16import { useIsRestoring } from './isRestoring'
17import type { QueryOptions, UseQueryResult } from './types'
18import type { Accessor } from 'solid-js'
19import type { QueryClient } from './QueryClient'
20import type {
21 DefaultError,
22 OmitKeyof,
23 QueriesObserverOptions,
24 QueriesPlaceholderDataFunction,
25 QueryFunction,
26 QueryKey,
27 QueryObserverOptions,
28 QueryObserverResult,
29 ThrowOnError,
30} from '@tanstack/query-core'
31​
32// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
33// `placeholderData` function does not have a parameter
34type UseQueryOptionsForUseQueries<
35 TQueryFnData = unknown,
36 TError = DefaultError,
37 TData = TQueryFnData,
38 TQueryKey extends QueryKey = QueryKey,
39> = OmitKeyof<
40 QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
41 'placeholderData' | 'suspense'
42> & {
43 placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>
44 /**
45 * @deprecated The `suspense` option has been deprecated in v5 and will be removed in the next major version.
46 * The `data` property on useQueries is a plain object and not a SolidJS Resource.
47 * It will not suspend when the data is loading.
48 * Setting `suspense` to `true` will be a no-op.
49 */
50 suspense?: boolean
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 GetOptions<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​
95type GetResults<T> =
96 // Part 1: responsible for mapping explicit type parameter to function result, if object
97 T extends { queryFnData: any; error?: infer TError; data: infer TData }
98 ? UseQueryResult<TData, TError>
99 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
100 ? UseQueryResult<TQueryFnData, TError>
101 : T extends { data: infer TData; error?: infer TError }
102 ? UseQueryResult<TData, TError>
103 : // Part 2: responsible for mapping explicit type parameter to function result, if tuple
104 T extends [any, infer TError, infer TData]
105 ? UseQueryResult<TData, TError>
106 : T extends [infer TQueryFnData, infer TError]
107 ? UseQueryResult<TQueryFnData, TError>
108 : T extends [infer TQueryFnData]
109 ? UseQueryResult<TQueryFnData>
110 : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
111 T extends {
112 queryFn?:
113 | QueryFunction<infer TQueryFnData, any>
114 | SkipTokenForUseQueries
115 select?: (data: any) => infer TData
116 throwOnError?: ThrowOnError<any, infer TError, any, any>
117 }
118 ? UseQueryResult<
119 unknown extends TData ? TQueryFnData : TData,
120 unknown extends TError ? DefaultError : TError
121 >
122 : // Fallback
123 UseQueryResult
124​
125/**
126 * QueriesOptions reducer recursively unwraps function arguments to infer/enforce type param
127 */
128type QueriesOptions<
129 T extends Array<any>,
130 TResult extends Array<any> = [],
131 TDepth extends ReadonlyArray<number> = [],
132> = TDepth['length'] extends MAXIMUM_DEPTH
133 ? Array<UseQueryOptionsForUseQueries>
134 : T extends []
135 ? []
136 : T extends [infer Head]
137 ? [...TResult, GetOptions<Head>]
138 : T extends [infer Head, ...infer Tail]
139 ? QueriesOptions<
140 [...Tail],
141 [...TResult, GetOptions<Head>],
142 [...TDepth, 1]
143 >
144 : ReadonlyArray<unknown> extends T
145 ? T
146 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
147 // use this to infer the param types in the case of Array.map() argument
148 T extends Array<
149 UseQueryOptionsForUseQueries<
150 infer TQueryFnData,
151 infer TError,
152 infer TData,
153 infer TQueryKey
154 >
155 >
156 ? Array<
157 UseQueryOptionsForUseQueries<
158 TQueryFnData,
159 TError,
160 TData,
161 TQueryKey
162 >
163 >
164 : // Fallback
165 Array<UseQueryOptionsForUseQueries>
166​
167/**
168 * QueriesResults reducer recursively maps type param to results
169 */
170type QueriesResults<
171 T extends Array<any>,
172 TResult extends Array<any> = [],
173 TDepth extends ReadonlyArray<number> = [],
174> = TDepth['length'] extends MAXIMUM_DEPTH
175 ? Array<UseQueryResult>
176 : T extends []
177 ? []
178 : T extends [infer Head]
179 ? [...TResult, GetResults<Head>]
180 : T extends [infer Head, ...infer Tail]
181 ? QueriesResults<
182 [...Tail],
183 [...TResult, GetResults<Head>],
184 [...TDepth, 1]
185 >
186 : { [K in keyof T]: GetResults<T[K]> }
187​
188/**
189 * The `useQueries` primitive can be used to fetch a variable number of queries.
190 *
191 * The `queries` key accepts an array with query option objects mostly identical to `useQuery` β€” see
192 * `placeholderData` below for the one difference. A custom `QueryClient` is supplied once, as `useQueries`'
193 * own top-level second argument, rather than per query.
194 *
195 * Having the same query key more than once in the array of query objects may cause some data to be shared
196 * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
197 * structure.
198 *
199 * The `combine` option can be used to combine the results of the queries into a single value. The result will
200 * be structurally shared to be as referentially stable as possible.
201 *
202 * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
203 * previously rendered queries, because the number of queries can differ between renders.
204 * @param queriesOptions - An accessor returning the `queries` array to run, and an optional `combine`
205 * function.
206 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
207 * will be used.
208 * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
209 * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
210 * @example
211 * ```tsx
212 * import { For } from 'solid-js'
213 * import { useQueries } from '@tanstack/solid-query'
214 *
215 * function Posts(props: { ids: Array<number> }) {
216 * const postQueries = useQueries(() => ({
217 * queries: props.ids.map((id) => ({
218 * queryKey: ['post', id],
219 * queryFn: () => fetchPost(id),
220 * staleTime: Infinity,
221 * })),
222 * }))
223 *
224 * return (
225 * <ul>
226 * <For each={postQueries}>
227 * {(postQuery) => {
228 * if (postQuery.isPending) return <li>Loading...</li>
229 * if (postQuery.isError) return <li>Error: {postQuery.error.message}</li>
230 * return <li>{postQuery.data.title}</li>
231 * }}
232 * </For>
233 * </ul>
234 * )
235 * }
236 * ```
237 * @example
238 * Combining results into a single value:
239 * ```tsx
240 * import { For, Match, Switch } from 'solid-js'
241 * import { useQueries } from '@tanstack/solid-query'
242 *
243 * function Posts(props: { ids: Array<number> }) {
244 * const combinedPostsQuery = useQueries(() => ({
245 * queries: props.ids.map((id) => ({
246 * queryKey: ['post', id],
247 * queryFn: () => fetchPost(id),
248 * })),
249 * combine: (postQueries) => {
250 * return {
251 * data: postQueries.map((postQuery) => postQuery.data),
252 * isPending: postQueries.some((postQuery) => postQuery.isPending),
253 * isError: postQueries.some((postQuery) => postQuery.isError),
254 * }
255 * },
256 * }))
257 *
258 * return (
259 * <Switch
260 * fallback={
261 * <ul>
262 * <For each={combinedPostsQuery.data}>{(post) => <li>{post?.title}</li>}</For>
263 * </ul>
264 * }
265 * >
266 * <Match when={combinedPostsQuery.isPending}>Loading...</Match>
267 * <Match when={combinedPostsQuery.isError}>Error loading posts</Match>
268 * </Switch>
269 * )
270 * }
271 * ```
272 */
273export function useQueries<
274 T extends Array<any>,
275 TCombinedResult extends QueriesResults<T> = QueriesResults<T>,
276>(
277 queriesOptions: Accessor<{
278 queries:
279 | readonly [...QueriesOptions<T>]
280 | readonly [...{ [K in keyof T]: GetOptions<T[K]> }]
281 combine?: (result: QueriesResults<T>) => TCombinedResult
282 }>,
283 queryClient?: Accessor<QueryClient>,
284): TCombinedResult {
285 const resolveClient = useQueryClientResolver(queryClient)
286 const client = createMemo(() => resolveClient())
287 const isRestoring = useIsRestoring()
288​
289 const defaultedQueries = createMemo(() =>
290 queriesOptions().queries.map((options) =>
291 mergeProps(
292 client().defaultQueryOptions(options as QueryObserverOptions),
293 {
294 get _optimisticResults() {
295 return isRestoring() ? 'isRestoring' : 'optimistic'
296 },
297 },
298 ),
299 ),
300 )
301​
302 const [observer, setObserver] = createSignal(
303 new QueriesObserver(
304 client(),
305 defaultedQueries(),
306 queriesOptions().combine
307 ? ({
308 combine: queriesOptions().combine,
309 } as QueriesObserverOptions<TCombinedResult>)
310 : undefined,
311 ),
312 )
313​
314 const [state, setState] = createStore<TCombinedResult>(
315 observer().getOptimisticResult(
316 defaultedQueries(),
317 (queriesOptions() as QueriesObserverOptions<TCombinedResult>).combine,
318 )[1](),
319 )
320​
321 createComputed(
322 on(
323 client,
324 (c) => {
325 const newObserver = new QueriesObserver(
326 c,
327 defaultedQueries(),
328 queriesOptions().combine
329 ? ({
330 combine: queriesOptions().combine,
331 } as QueriesObserverOptions<TCombinedResult>)
332 : undefined,
333 )
334 setObserver(newObserver)
335 setState(
336 newObserver.getOptimisticResult(
337 defaultedQueries(),
338 (queriesOptions() as QueriesObserverOptions<TCombinedResult>)
339 .combine,
340 )[1](),
341 )
342 },
343 { defer: true },
344 ),
345 )
346​
347 createRenderEffect(
348 on(
349 () => queriesOptions().queries.length,
350 () =>
351 setState(
352 observer().getOptimisticResult(
353 defaultedQueries(),
354 (queriesOptions() as QueriesObserverOptions<TCombinedResult>)
355 .combine,
356 )[1](),
357 ),
358 ),
359 )
360​
361 const dataResources = createMemo(
362 on(
363 () => state.length,
364 () =>
365 state.map((queryRes) => {
366 const dataPromise = () =>
367 new Promise((resolve) => {
368 if (queryRes.isFetching && queryRes.isLoading) return
369 resolve(unwrap(queryRes.data))
370 })
371 return createResource(dataPromise)
372 }),
373 ),
374 )
375​
376 batch(() => {
377 const dataResources_ = dataResources()
378 for (let index = 0; index < dataResources_.length; index++) {
379 const dataResource = dataResources_[index]!
380 dataResource[1].mutate(() => unwrap(state[index]!.data))
381 dataResource[1].refetch()
382 }
383 })
384​
385 let taskQueue: Array<() => void> = []
386 const subscribeToObserver = () =>
387 observer().subscribe((result) => {
388 taskQueue.push(() => {
389 batch(() => {
390 const dataResources_ = dataResources()
391 for (let index = 0; index < dataResources_.length; index++) {
392 const dataResource = dataResources_[index]!
393 const unwrappedResult = { ...unwrap(result[index]) }
394 // @ts-expect-error typescript pedantry regarding the possible range of index
395 setState(index, unwrap(unwrappedResult))
396 dataResource[1].mutate(() => unwrap(state[index]!.data))
397 dataResource[1].refetch()
398 }
399 })
400 })
401​
402 queueMicrotask(() => {
403 const taskToRun = taskQueue.pop()
404 if (taskToRun) taskToRun()
405 taskQueue = []
406 })
407 })
408​
409 let unsubscribe: () => void = noop
410 createComputed<() => void>((cleanup) => {
411 cleanup?.()
412 unsubscribe = isRestoring() ? noop : subscribeToObserver()
413 // cleanup needs to be scheduled after synchronous effects take place
414 return () => queueMicrotask(unsubscribe)
415 })
416 onCleanup(() => unsubscribe())
417​
418 onMount(() => {
419 observer().setQueries(
420 defaultedQueries(),
421 queriesOptions().combine
422 ? ({
423 combine: queriesOptions().combine,
424 } as QueriesObserverOptions<TCombinedResult>)
425 : undefined,
426 )
427 })
428​
429 createComputed(() => {
430 observer().setQueries(
431 defaultedQueries(),
432 queriesOptions().combine
433 ? ({
434 combine: queriesOptions().combine,
435 } as QueriesObserverOptions<TCombinedResult>)
436 : undefined,
437 )
438 })
439​
440 const handler = (index: number) => ({
441 get(target: QueryObserverResult, prop: keyof QueryObserverResult): any {
442 if (prop === 'data') {
443 return dataResources()[index]![0]()
444 }
445 return Reflect.get(target, prop)
446 },
447 })
448​
449 const getProxies = () =>
450 state.map((s, index) => {
451 return new Proxy(s, handler(index))
452 })
453​
454 const [proxyState, setProxyState] = createStore(getProxies())
455 createRenderEffect(() => setProxyState(getProxies()))
456​
457 return proxyState as TCombinedResult