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

useQueries.md

204 lines9.1 KB

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