Open History to see the last commit
1import { QueryObserver } from '@tanstack/query-core'
2import { $TRACK, createMemo, repeat } from 'solid-js'
3import { useBaseQuery } from './useBaseQuery'
4import type { QueryOptions, UseQueryResult } from './types'
5import type { Accessor } from 'solid-js'
6import type { QueryClient } from './QueryClient'
7import type {
8 DefaultError,
9 OmitKeyof,
10 QueriesPlaceholderDataFunction,
11 QueryFunction,
12 QueryKey,
13 ThrowOnError,
14} from '@tanstack/query-core'
15β
16// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
17// `placeholderData` function does not have a parameter
18type UseQueryOptionsForUseQueries<
19 TQueryFnData = unknown,
20 TError = DefaultError,
21 TData = TQueryFnData,
22 TQueryKey extends QueryKey = QueryKey,
23> = OmitKeyof<
24 QueryOptions<TQueryFnData, TError, TData, TQueryKey>,
25 'placeholderData'
26> & {
27 placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>
28 /**
29 * @deprecated The `suspense` option has been removed. Suspense is the
30 * model: each result's `data` is an async read that suspends into the
31 * nearest `<Loading>` boundary while its first fetch is in flight, same
32 * as `useQuery`. Setting `suspense` is a no-op.
33 */
34 suspense?: boolean
35}
36β
37// Avoid TS depth-limit error in case of large array literal
38type MAXIMUM_DEPTH = 20
39β
40// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
41type SkipTokenForUseQueries = symbol
42β
43type GetOptions<T> =
44 // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
45 T extends {
46 queryFnData: infer TQueryFnData
47 error?: infer TError
48 data: infer TData
49 }
50 ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
51 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
52 ? UseQueryOptionsForUseQueries<TQueryFnData, TError>
53 : T extends { data: infer TData; error?: infer TError }
54 ? UseQueryOptionsForUseQueries<unknown, TError, TData>
55 : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
56 T extends [infer TQueryFnData, infer TError, infer TData]
57 ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>
58 : T extends [infer TQueryFnData, infer TError]
59 ? UseQueryOptionsForUseQueries<TQueryFnData, TError>
60 : T extends [infer TQueryFnData]
61 ? UseQueryOptionsForUseQueries<TQueryFnData>
62 : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
63 T extends {
64 queryFn?:
65 | QueryFunction<infer TQueryFnData, infer TQueryKey>
66 | SkipTokenForUseQueries
67 select?: (data: any) => infer TData
68 throwOnError?: ThrowOnError<any, infer TError, any, any>
69 }
70 ? UseQueryOptionsForUseQueries<
71 TQueryFnData,
72 unknown extends TError ? DefaultError : TError,
73 unknown extends TData ? TQueryFnData : TData,
74 TQueryKey
75 >
76 : // Fallback
77 UseQueryOptionsForUseQueries
78β
79type GetResults<T> =
80 // Part 1: responsible for mapping explicit type parameter to function result, if object
81 T extends { queryFnData: any; error?: infer TError; data: infer TData }
82 ? UseQueryResult<TData, TError>
83 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
84 ? UseQueryResult<TQueryFnData, TError>
85 : T extends { data: infer TData; error?: infer TError }
86 ? UseQueryResult<TData, TError>
87 : // Part 2: responsible for mapping explicit type parameter to function result, if tuple
88 T extends [any, infer TError, infer TData]
89 ? UseQueryResult<TData, TError>
90 : T extends [infer TQueryFnData, infer TError]
91 ? UseQueryResult<TQueryFnData, TError>
92 : T extends [infer TQueryFnData]
93 ? UseQueryResult<TQueryFnData>
94 : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
95 T extends {
96 queryFn?:
97 | QueryFunction<infer TQueryFnData, any>
98 | SkipTokenForUseQueries
99 select?: (data: any) => infer TData
100 throwOnError?: ThrowOnError<any, infer TError, any, any>
101 }
102 ? UseQueryResult<
103 unknown extends TData ? TQueryFnData : TData,
104 unknown extends TError ? DefaultError : TError
105 >
106 : // Fallback
107 UseQueryResult
108β
109/**
110 * QueriesOptions reducer recursively snapshots function arguments to infer/enforce type param
111 */
112type QueriesOptions<
113 T extends Array<any>,
114 TResult extends Array<any> = [],
115 TDepth extends ReadonlyArray<number> = [],
116> = TDepth['length'] extends MAXIMUM_DEPTH
117 ? Array<UseQueryOptionsForUseQueries>
118 : T extends []
119 ? []
120 : T extends [infer Head]
121 ? [...TResult, GetOptions<Head>]
122 : T extends [infer Head, ...infer Tail]
123 ? QueriesOptions<
124 [...Tail],
125 [...TResult, GetOptions<Head>],
126 [...TDepth, 1]
127 >
128 : ReadonlyArray<unknown> extends T
129 ? T
130 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
131 // use this to infer the param types in the case of Array.map() argument
132 T extends Array<
133 UseQueryOptionsForUseQueries<
134 infer TQueryFnData,
135 infer TError,
136 infer TData,
137 infer TQueryKey
138 >
139 >
140 ? Array<
141 UseQueryOptionsForUseQueries<
142 TQueryFnData,
143 TError,
144 TData,
145 TQueryKey
146 >
147 >
148 : // Fallback
149 Array<UseQueryOptionsForUseQueries>
150β
151/**
152 * QueriesResults reducer recursively maps type param to results
153 */
154type QueriesResults<
155 T extends Array<any>,
156 TResult extends Array<any> = [],
157 TDepth extends ReadonlyArray<number> = [],
158> = TDepth['length'] extends MAXIMUM_DEPTH
159 ? Array<UseQueryResult>
160 : T extends []
161 ? []
162 : T extends [infer Head]
163 ? [...TResult, GetResults<Head>]
164 : T extends [infer Head, ...infer Tail]
165 ? QueriesResults<
166 [...Tail],
167 [...TResult, GetResults<Head>],
168 [...TDepth, 1]
169 >
170 : { [K in keyof T]: GetResults<T[K]> }
171β
172/**
173 * The `useQueries` primitive can be used to fetch a variable number of queries.
174 *
175 * The `queries` key accepts an array with query option objects mostly identical to `useQuery` β see
176 * `placeholderData` below for the one difference. A custom `QueryClient` is supplied once, as `useQueries`'
177 * own top-level second argument, rather than per query.
178 *
179 * Having the same query key more than once in the array of query objects may cause some data to be shared
180 * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
181 * structure.
182 *
183 * The `combine` option can be used to combine the results of the queries into a single value. The result will
184 * be structurally shared to be as referentially stable as possible.
185 *
186 * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
187 * previously rendered queries, because the number of queries can differ between renders.
188 * @param queriesOptions - An accessor returning the `queries` array to run, and an optional `combine`
189 * function.
190 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
191 * will be used.
192 * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
193 * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
194 * @example
195 * ```tsx
196 * import { For } from 'solid-js'
197 * import { useQueries } from '@tanstack/solid-query'
198 *
199 * function Posts(props: { ids: Array<number> }) {
200 * const postQueries = useQueries(() => ({
201 * queries: props.ids.map((id) => ({
202 * queryKey: ['post', id],
203 * queryFn: () => fetchPost(id),
204 * staleTime: Infinity,
205 * })),
206 * }))
207 *
208 * return (
209 * <ul>
210 * <For each={postQueries}>
211 * {(postQuery) => {
212 * if (postQuery.isPending) return <li>Loading...</li>
213 * if (postQuery.isError) return <li>Error: {postQuery.error.message}</li>
214 * return <li>{postQuery.data.title}</li>
215 * }}
216 * </For>
217 * </ul>
218 * )
219 * }
220 * ```
221 * @example
222 * Combining results into a single value:
223 * ```tsx
224 * import { For, Match, Switch } from 'solid-js'
225 * import { useQueries } from '@tanstack/solid-query'
226 *
227 * function Posts(props: { ids: Array<number> }) {
228 * const combinedPostsQuery = useQueries(() => ({
229 * queries: props.ids.map((id) => ({
230 * queryKey: ['post', id],
231 * queryFn: () => fetchPost(id),
232 * })),
233 * combine: (postQueries) => {
234 * return {
235 * data: postQueries.map((postQuery) => postQuery.data),
236 * isPending: postQueries.some((postQuery) => postQuery.isPending),
237 * isError: postQueries.some((postQuery) => postQuery.isError),
238 * }
239 * },
240 * }))
241 *
242 * return (
243 * <Switch
244 * fallback={
245 * <ul>
246 * <For each={combinedPostsQuery.data}>{(post) => <li>{post?.title}</li>}</For>
247 * </ul>
248 * }
249 * >
250 * <Match when={combinedPostsQuery.isPending}>Loading...</Match>
251 * <Match when={combinedPostsQuery.isError}>Error loading posts</Match>
252 * </Switch>
253 * )
254 * }
255 * ```
256 */
257export function useQueries<
258 T extends Array<any>,
259 TCombinedResult = QueriesResults<T>,
260>(
261 queriesOptions: Accessor<{
262 queries:
263 | readonly [...QueriesOptions<T>]
264 | readonly [...{ [K in keyof T]: GetOptions<T[K]> }]
265 combine?: (result: QueriesResults<T>) => TCombinedResult
266 }>,
267 queryClient?: Accessor<QueryClient>,
268): TCombinedResult {
269 /**
270 * One read layer per position, count-keyed: each row owns a full
271 * `useBaseQuery` (observer lifecycle, version signal, async data node)
272 * whose options stay reactive through the per-index accessor β option
273 * changes flow into the existing row without tearing it down, while
274 * length changes create/dispose tail rows. Every result has identical
275 * semantics to `useQuery`: reads suspend, settled data is non-nullable.
276 */
277 const length = createMemo(() => queriesOptions().queries.length)
278 const results = repeat(length, (index) => {
279 // When the array shrinks, cache events can reach this row's
280 // subscriptions before disposal runs; the row keeps answering with its
281 // last options rather than reading past the end of the shorter array.
282 let lastOptions: any
283 return useBaseQuery(
284 () => {
285 const next = queriesOptions().queries[index]
286 if (next !== undefined) lastOptions = next
287 return lastOptions
288 },
289 QueryObserver,
290 queryClient,
291 )
292 })
293β
294 const combined = createMemo(() => {
295 const combine = queriesOptions().combine
296 const list = results() as unknown as QueriesResults<T>
297 return combine ? combine(list) : (list as unknown as TCombinedResult)
298 })
299β
300 // A stable facade over the combined result. Property reads pull through
301 // the memo so consumers track exactly what they touch; $TRACK hands list
302 // helpers (<For>, mapArray) the underlying array for diffing.
303 return new Proxy([] as unknown as TCombinedResult & object, {
304 get(_, prop) {
305 if (prop === $TRACK) return combined()
306 return Reflect.get(combined() as object, prop)
307 },
308 has(_, prop) {
309 if (prop === $TRACK) return true
310 return Reflect.has(combined() as object, prop)
311 },
312 ownKeys() {
313 return Reflect.ownKeys(combined() as object)
314 },
315 getOwnPropertyDescriptor(_, prop) {
316 const descriptor = Reflect.getOwnPropertyDescriptor(
317 combined() as object,
318 prop,
319 )
320 if (descriptor) descriptor.configurable = true
321 return descriptor
322 },
323 })
324}