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

useQueries.md

55 lines2.1 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], queryFn: () => fetchPost(id), staleTime: Infinity },
13 )),
14})
15```
16​
17**Options**
18​
19The `useQueries` hook accepts an options object with a **queries** key whose value is an array with query option objects identical to the [`useQuery` hook](./reference/useQuery) (excluding the `queryClient` option - because the `QueryClient` can be passed in on the top level).
20​
21- `queryClient?: QueryClient`
22 - Use this to provide a custom QueryClient. Otherwise, the one from the nearest context will be used.
23- `combine?: (result: UseQueriesResults) => TCombinedResult`
24 - Use this to combine the results of the queries into a single value.
25​
26> 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.
27​
28**placeholderData**
29​
30The `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.
31​
32**Returns**
33​
34The `useQueries` hook returns an array with all the query results. The order returned is the same as the input order.
35​
36## Combine
37​
38If 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.
39​
40```tsx
41const ids = [1,2,3]
42const combinedQueries = useQueries({
43 queries: ids.map(id => (
44 { queryKey: ['post', id], queryFn: () => fetchPost(id) },
45 )),
46 combine: (results) => {
47 return ({
48 data: results.map(result => result.data),
49 pending: results.some(result => result.isPending),
50 })
51 }
52})
53```
54​
55In 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.