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

dependent-queries.md

53 lines1012 Bytes

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: 'loading'
38fetchStatus: 'idle'
39```
40​
41As soon as the `user` is available, the `projects` query will be `enabled` and will then transition to:
42​
43```tsx
44status: 'loading'
45fetchStatus: 'fetching'
46```
47​
48Once we have the projects, it will go to:
49​
50```tsx
51status: 'success'
52fetchStatus: 'idle'
53```