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

dependent-queries.md

56 lines1.0 KB

1---
2id: dependent-queries
3title: Dependent Queries
4---
5​
6Dependent (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:
7​
8[//]: # 'Example'
9​
10```tsx
11// Get the user
12const { data: user } = useQuery({
13 queryKey: ['user', email],
14 queryFn: getUserByEmail,
15})
16​
17const userId = user?.id
18​
19// Then get the user's projects
20const {
21 status,
22 fetchStatus,
23 data: projects,
24} = useQuery({
25 queryKey: ['projects', userId],
26 queryFn: getProjectsByUser,
27 // The query will not execute until the userId exists
28 enabled: !!userId,
29})
30```
31​
32[//]: # 'Example'
33​
34The `projects` query will start in:
35​
36```tsx
37status: 'pending'
38isPending: false
39fetchStatus: 'idle'
40```
41​
42As soon as the `user` is available, the `projects` query will be `enabled` and will then transition to:
43​
44```tsx
45status: 'pending'
46isPending: true
47fetchStatus: 'fetching'
48```
49​
50Once we have the projects, it will go to:
51​
52```tsx
53status: 'success'
54isPending: false
55fetchStatus: 'idle'
56```