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

dependent-queries.md

51 lines1.1 KB

1---
2id: dependent-queries
3title: Dependent Queries
4ref: docs/framework/react/guides/dependent-queries.md
5---
6​
7[//]: # 'Example'
8​
9```tsx
10// Get the user
11const userQuery = useQuery(() => ({
12 queryKey: ['user', email],
13 queryFn: getUserByEmail,
14}))
15​
16const userId = () => userQuery.data?.id
17​
18// Then get the user's projects
19const projectsQuery = useQuery(() => ({
20 queryKey: ['projects', userId()],
21 queryFn: getProjectsByUser,
22 // The query will not execute until the userId exists
23 enabled: !!userId(),
24}))
25```
26​
27[//]: # 'Example'
28[//]: # 'Example2'
29​
30```tsx
31// Get the users ids
32const usersQuery = useQuery(() => ({
33 queryKey: ['users'],
34 queryFn: getUsersData,
35 select: (users) => users.map((user) => user.id),
36}))
37​
38// Then get the users messages
39const usersMessages = useQueries(() => ({
40 queries: usersQuery.data
41 ? usersQuery.data.map((id) => {
42 return {
43 queryKey: ['messages', id],
44 queryFn: () => getMessagesByUsers(id),
45 }
46 })
47 : [], // if usersQuery.data is undefined, an empty array will be returned
48}))
49```
50​
51[//]: # 'Example2'