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

useQueries.md

202 lines8.4 KB

1---
2id: useQueries
3title: useQueries
4redirect_from:
5 - framework/react/reference/useQueries
6---
7​
8```ts
9function useQueries<T, TCombinedResult>(options: object, queryClient?: QueryClient): TCombinedResult;
10```
11​
12Defined in: [packages/react-query/src/useQueries.ts:356](https://github.com/TanStack/query/blob/main/packages/react-query/src/useQueries.ts#L356)
13​
14The `useQueries` hook can be used to fetch a variable number of queries.
15​
16The `queries` key accepts an array with query option objects mostly identical to `useQuery` β€” the top-level
17`subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom
18`QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query.
19​
20Having the same query key more than once in the array of query objects may cause some data to be shared
21between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
22structure.
23​
24The `combine` option can be used to combine the results of the queries into a single value. The result will
25be structurally shared to be as referentially stable as possible.
26​
27## Type Parameters
28​
29### T
30​
31`T` *extends* `any`[]
32​
33### TCombinedResult
34​
35`TCombinedResult` = `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \[...\{ \[K in string \| number \| symbol\]: GetUseQueryResult\<Tails\[K\]\> \}\[\]\] : \{ \[K in string \| number \| symbol\]: GetUseQueryResult\<T\[K\]\> \}
36​
37## Parameters
38​
39### options
40​
41The `queries` array to run, and the optional `combine` and `subscribed` options.
42​
43#### combine?
44​
45(`result`: `T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryResult`\<`Head`\>, `GetUseQueryResult`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : \[`...{ [K in (...)]: (...) }[]`\] : \{ \[K in string \| number \| symbol\]: GetUseQueryResult\<T\[K\]\> \}) => `TCombinedResult`
46​
47Use this to combine the results of the queries into a single value. The result will be structurally
48shared to be as referentially stable as possible.
49​
50#### queries
51​
52 \| readonly \[`T` *extends* \[\] ? \[\] : `T` *extends* \[`Head`\] ? \[`GetUseQueryOptionsForUseQueries`\<`Head`\>\] : `T` *extends* \[`Head`, `...Tails[]`\] ? \[`...Tails[]`\] *extends* \[\] ? \[\] : \[`...Tails[]`\] *extends* \[`Head`\] ? \[`GetUseQueryOptionsForUseQueries`\<`Head`\>, `GetUseQueryOptionsForUseQueries`\<`Head`\>\] : \[`...Tails[]`\] *extends* \[`Head`, `...Tails[]`\] ? \[`...(...)[]`\] *extends* \[\] ? \[\] : ... *extends* ... ? ... : ... : readonly ...[] *extends* \[`...(...)[]`\] ? \[`...(...)[]`\] : ... *extends* ... ? ... : ... : readonly `unknown`[] *extends* `T` ? `T` : `T` *extends* `UseQueryOptionsForUseQueries`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] ? `UseQueryOptionsForUseQueries`\<`TQueryFnData`, `TError`, `TData`, `TQueryKey`\>[] : `UseQueryOptionsForUseQueries`\<`unknown`, `Error`, `unknown`, readonly ...[]\>[]\]
53 \| readonly \[\{ \[K in string \| number \| symbol\]: GetUseQueryOptionsForUseQueries\<T\[K\]\> \}\]
54​
55An array with query option objects, mostly identical to `useQuery` β€” except that `queryClient` and
56`subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and
57`placeholderData` accepts a [QueriesPlaceholderDataFunction](../type-aliases/QueriesPlaceholderDataFunction.md), which is called with `previousData`
58and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.
59​
60#### subscribed?
61​
62`boolean`
63​
64Set this to `false` to unsubscribe this observer from updates to the query cache.
65​
66**Default Value**
67​
68```ts
69true
70```
71​
72### queryClient?
73​
74[`QueryClient`](../classes/QueryClient.md)
75​
76Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context
77will be used.
78​
79## Returns
80​
81`TCombinedResult`
82​
83The combined result. Without `combine`, this is an array with all the query results, in the same
84order as the input. When `combine` is provided, this is the value returned by `combine` instead.
85​
86## Throws
87​
88The error of the first query that should be thrown to the nearest error boundary (see
89`throwOnError`). While suspending, it throws a promise instead.
90​
91## Remarks
92​
93The `combine` function only re-runs if it changed referentially, or if any of the query results
94changed. An inlined `combine` function, as shown in the example below, therefore runs on every render β€” wrap
95it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to
96avoid that.
97​
98Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling
99`queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter
100of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls
101back to `unknown` β€” a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate
102the `select` parameter explicitly, or define the query with [queryOptions](queryOptions.md), which resolves its types in
103a single object _before_ it reaches `useQueries`, to work around this β€” see the example below. The same
104limitation applies to [useSuspenseQueries](useSuspenseQueries.md).
105​
106`placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
107previously rendered queries, because the number of queries can differ between renders.
108​
109## Examples
110​
111```tsx
112import { useQueries } from '@tanstack/react-query'
113​
114function Posts({ ids }: { ids: Array<number> }) {
115 const postQueries = useQueries({
116 queries: ids.map((id) => ({
117 queryKey: ['post', id],
118 queryFn: () => fetchPost(id),
119 staleTime: Infinity,
120 })),
121 })
122​
123 return (
124 <ul>
125 {postQueries.map((query, index) => {
126 if (query.isPending) return <li key={ids[index]}>Loading...</li>
127 if (query.isError) return <li key={ids[index]}>Error: {query.error.message}</li>
128 return <li key={ids[index]}>{query.data.title}</li>
129 })}
130 </ul>
131 )
133```
134​
135Combining results into a single value:
136```tsx
137import { useQueries } from '@tanstack/react-query'
138​
139function Posts({ ids }: { ids: Array<number> }) {
140 const { data, isPending, isError } = useQueries({
141 queries: ids.map((id) => ({
142 queryKey: ['post', id],
143 queryFn: () => fetchPost(id),
144 })),
145 combine: (postQueries) => {
146 return {
147 data: postQueries.map((query) => query.data),
148 isPending: postQueries.some((query) => query.isPending),
149 isError: postQueries.some((query) => query.isError),
150 }
151 },
152 })
153​
154 if (isPending) return 'Loading...'
155 if (isError) return 'Error loading posts'
156​
157 return (
158 <ul>
159 {data.map((post) => (
160 <li key={post?.id}>{post?.title}</li>
161 ))}
162 </ul>
163 )
165```
166​
167Typing `select` via [queryOptions](queryOptions.md). Note that spreading a `queryOptions` result and overriding
168`select` inline still falls back to `unknown` β€” wrap the spread in `queryOptions` again so the override is
169resolved before it reaches `useQueries`:
170```tsx
171import { queryOptions, useQueries } from '@tanstack/react-query'
172​
173const postOptions = (id: number) =>
174 queryOptions({
175 queryKey: ['post', id],
176 queryFn: () => fetchPost(id),
177 })
178​
179function PostTitle({ id }: { id: number }) {
180 const [{ data: broken }] = useQueries({
181 queries: [
182 {
183 ...postOptions(id),
184 // ❌ `data` is `unknown` here
185 select: (data) => data.title,
186 },
187 ],
188 })
189​
190 const [{ data: fixed }] = useQueries({
191 queries: [
192 queryOptions({
193 ...postOptions(id),
194 // βœ… `data` is `Post`
195 select: (data) => data.title,
196 }),
197 ],
198 })
199​
200 return <h1>{fixed}</h1>
202```