依赖(或串行)查询依赖于前一个查询完成后才能执行。为了实现这一点,只需使用 enabled 选项来告诉查询何时可以运行
// Get the user
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: getUserByEmail,
})
const userId = user?.id
// Then get the user's projects
const {
status,
fetchStatus,
data: projects,
} = useQuery({
queryKey: ['projects', userId],
queryFn: getProjectsByUser,
// The query will not execute until the userId exists
enabled: !!userId,
})
// Get the user
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: getUserByEmail,
})
const userId = user?.id
// Then get the user's projects
const {
status,
fetchStatus,
data: projects,
} = useQuery({
queryKey: ['projects', userId],
queryFn: getProjectsByUser,
// The query will not execute until the userId exists
enabled: !!userId,
})
当 projects 查询开始时
status: 'pending'
isPending: true
fetchStatus: 'idle'
status: 'pending'
isPending: true
fetchStatus: 'idle'
一旦 user 可用,projects 查询将被 启用,然后将转换为
status: 'pending'
isPending: true
fetchStatus: 'fetching'
status: 'pending'
isPending: true
fetchStatus: 'fetching'
一旦我们有了项目,它将进入
status: 'success'
isPending: false
fetchStatus: 'idle'
status: 'success'
isPending: false
fetchStatus: 'idle'
动态并行查询 - useQueries 也可以依赖于先前的查询,以下是如何实现这一点
// Get the users ids
const { data: userIds } = useQuery({
queryKey: ['users'],
queryFn: getUsersData,
select: (users) => users.map((user) => user.id),
})
// Then get the users messages
const usersMessages = useQueries({
queries: userIds
? userIds.map((id) => {
return {
queryKey: ['messages', id],
queryFn: () => getMessagesByUsers(id),
}
})
: [], // if userIds is undefined, an empty array will be returned
})
// Get the users ids
const { data: userIds } = useQuery({
queryKey: ['users'],
queryFn: getUsersData,
select: (users) => users.map((user) => user.id),
})
// Then get the users messages
const usersMessages = useQueries({
queries: userIds
? userIds.map((id) => {
return {
queryKey: ['messages', id],
queryFn: () => getMessagesByUsers(id),
}
})
: [], // if userIds is undefined, an empty array will be returned
})
注意,useQueries 返回一个查询结果数组
依赖查询从定义上构成了请求瀑布的一种形式,这会损害性能。如果我们假设两个查询花费相同的时间,那么串行执行而不是并行执行总是需要两倍的时间,当发生在具有高延迟的客户端上时,这一点尤其有害。如果可以,最好重构后端 API,以便两个查询可以并行获取,尽管这可能并不总是实际可行。
在上面的示例中,与其先获取 getUserByEmail 才能 getProjectsByUser,不如引入一个新的 getProjectsByUserEmail 查询来扁平化瀑布。