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

useQueries.md

145 lines4.5 KB

1---
2id: useQueries
3title: useQueries
4---
5​
6The `useQueries` hook can be used to fetch a variable number of queries:
7​
8```tsx
9const ids = [1, 2, 3]
10const results = useQueries({
11 queries: ids.map((id) => ({
12 queryKey: ['post', id],
13 queryFn: () => fetchPost(id),
14 staleTime: Infinity,
15 })),
16})
17```
18​
19**Options**
20​
21The `useQueries` hook accepts an options object with a **queries** key whose value is an array with query option objects identical to the [`useQuery` hook](./useQuery.md) (excluding the `queryClient` option - because the `QueryClient` can be passed in on the top level).
22​
23- `queryClient?: QueryClient`
24 - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context will be used.
25- `combine?: (result: UseQueriesResults) => TCombinedResult`
26 - Use this to combine the results of the queries into a single value.
27​
28> Having the same query key more than once in the array of query objects may cause some data to be shared between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired structure.
29​
30**placeholderData**
31​
32The `placeholderData` option exists for `useQueries` as well, but it doesn't get information passed from previously rendered Queries like `useQuery` does, because the input to `useQueries` can be a different number of Queries on each render.
33​
34**Returns**
35​
36The `useQueries` hook returns an array with all the query results. The order returned is the same as the input order.
37​
38## Combine
39​
40If you want to combine `data` (or other Query information) from the results into a single value, you can use the `combine` option. The result will be structurally shared to be as referentially stable as possible.
41​
42```tsx
43const ids = [1, 2, 3]
44const combinedQueries = useQueries({
45 queries: ids.map((id) => ({
46 queryKey: ['post', id],
47 queryFn: () => fetchPost(id),
48 })),
49 combine: (results) => {
50 return {
51 data: results.map((result) => result.data),
52 pending: results.some((result) => result.isPending),
53 }
54 },
55})
56```
57​
58In the above example, `combinedQueries` will be an object with a `data` and a `pending` property. Note that all other properties of the Query results will be lost.
59​
60### Memoization
61​
62The `combine` function will only re-run if:
63​
64- the `combine` function itself changed referentially
65- any of the query results changed
66​
67This means that an inlined `combine` function, as shown above, will run on every render. To avoid this, you can wrap the `combine` function in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies.
68​
69## TypeScript: typing the `select` option
70​
71Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls back to `unknown`. This is a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556).
72​
73```tsx
74useQueries({
75 queries: [
76 {
77 queryKey: ['post', 1],
78 queryFn: () => fetchPost(1),
79 // ❌ `data` is `unknown` here
80 select: (data) => data.title,
81 },
82 ],
83})
84```
85​
86There are two supported workarounds:
87​
881. Annotate the `select` parameter explicitly:
89​
90```tsx
91useQueries({
92 queries: [
93 {
94 queryKey: ['post', 1],
95 queryFn: () => fetchPost(1),
96 // βœ… `data` is `Post`
97 select: (data: Post) => data.title,
98 },
99 ],
100})
101```
102​
1032. Define the query with the [`queryOptions`](./queryOptions.md) helper, which resolves its types in a single object _before_ it reaches `useQueries`:
104​
105```tsx
106const postOptions = (id: number) =>
107 queryOptions({
108 queryKey: ['post', id],
109 queryFn: () => fetchPost(id),
110 // βœ… `data` is `Post`
111 select: (data) => data.title,
112 })
113​
114useQueries({ queries: [postOptions(1), postOptions(2)] })
115```
116​
117The same limitation applies when you spread a `queryOptions` result to override its `select` inline β€” the overriding `select` still falls back to `unknown`:
118​
119```tsx
120useQueries({
121 queries: [
122 {
123 ...postOptions(1),
124 // ❌ `data` is `unknown` here
125 select: (data) => data.title,
126 },
127 ],
128})
129```
130​
131Wrap the spread in `queryOptions` again so the override is resolved before it reaches `useQueries`:
132​
133```tsx
134useQueries({
135 queries: [
136 queryOptions({
137 ...postOptions(1),
138 // βœ… `data` is `Post`
139 select: (data) => data.title,
140 }),
141 ],
142})
143```
144​
145The same applies to [`useSuspenseQueries`](./useSuspenseQueries.md).