React Query: How to make a query dependent on another
6 June 2022 (Updated 15 August 2022)
Use the enabled
option of useQuery
to disable a dependent query so that it only runs when a particular condition is met (e.g., another query has resolved).
// Get the user
const { data: user } = useQuery(['user', email], getUserByEmail)
const userId = user?.id
// Then get the user's projects
const { isIdle, data: projects } = useQuery(
['projects', userId],
getProjectsByUser,
{
// The query will not execute until the userId exists
enabled: !!userId,
}
)
// isIdle will be `true` until `enabled` is true and the query begins to fetch.
// It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :
Tagged:
React Query
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment