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

dependent-queries.md

95 lines2.5 KB

1---
2id: dependent-queries
3title: Dependent Queries
4---
5​
6## useQuery dependent Query
7​
8Dependent (or serial) queries depend on previous ones to finish before they can execute. To achieve this, it's as easy as using the `enabled` option to tell a query when it is ready to run:
9​
10[//]: # 'Example'
11​
12```tsx
13// Get the user
14const { data: user } = useQuery({
15 queryKey: ['user', email],
16 queryFn: getUserByEmail,
17})
18​
19const userId = user?.id
20​
21// Then get the user's projects
22const {
23 status,
24 fetchStatus,
25 data: projects,
26} = useQuery({
27 queryKey: ['projects', userId],
28 queryFn: getProjectsByUser,
29 // The query will not execute until the userId exists
30 enabled: !!userId,
31})
32```
33​
34[//]: # 'Example'
35​
36The `projects` query will start in:
37​
38```tsx
39status: 'pending'
40isPending: true
41fetchStatus: 'idle'
42```
43​
44As soon as the `user` is available, the `projects` query will be `enabled` and will then transition to:
45​
46```tsx
47status: 'pending'
48isPending: true
49fetchStatus: 'fetching'
50```
51​
52Once we have the projects, it will go to:
53​
54```tsx
55status: 'success'
56isPending: false
57fetchStatus: 'idle'
58```
59​
60## useQueries dependent Query
61​
62Dynamic parallel query - `useQueries` can depend on a previous query also, here's how to achieve this:
63​
64[//]: # 'Example2'
65​
66```tsx
67// Get the users ids
68const { data: userIds } = useQuery({
69 queryKey: ['users'],
70 queryFn: getUsersData,
71 select: (users) => users.map((user) => user.id),
72})
73​
74// Then get the users messages
75const usersMessages = useQueries({
76 queries: userIds
77 ? userIds.map((id) => {
78 return {
79 queryKey: ['messages', id],
80 queryFn: () => getMessagesByUsers(id),
81 }
82 })
83 : [], // if users is undefined, an empty array will be returned
84})
85```
86​
87[//]: # 'Example2'
88​
89**Note** that `useQueries` return an **array of query results**
90​
91## A note about performance
92​
93Dependent queries by definition constitutes a form of [request waterfall](./request-waterfalls.md), which hurts performance. If we pretend both queries take the same amount of time, doing them serially instead of in parallel always takes twice as much time, which is especially hurtful when it happens on a client that has high latency. If you can, it's always better to restructure the backend APIs so that both queries can be fetched in parallel, though that might not always be practically feasible.
94​
95In the example above, instead of first fetching `getUserByEmail` to be able to `getProjectsByUser`, introducing a new `getProjectsByUserEmail` query would flatten the waterfall.