I'm trying to use useQueries like this
function App({ users }) {
const userQueries = useQueries(
users.map(user => {
return {
queryKey: ['user', user.id],
queryFn: () => fetchUserById(user.id),
}
})
)
}
However, the users variable is being supplied by a useQuery and comes back undefined at first. This causes the error cannot read map of undefined. I want to add enabled like you can for useQuery, but I don't see it anywhere in the documentation. You can do it with a simple useQuery like this:
// 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 :)
essentially I want
function App({ users }) {
const userQueries = useQueries(
users.map(user => {
return {
queryKey: ['user', user.id],
queryFn: () => fetchUserById(user.id),
enabled: !!users
}
})
)
}
In React Query v4 the useQueries hook has been slightly modified (see: https://tanstack.com/query/v4/docs/guides/migrating-to-react-query-4#new-api-for-usequeries). Instead of passing the array directly, you need to pass an object with a query param:
const results = useQueries({
queries: [
{ queryKey: ['post', 1], queryFn: getProjectsByUser, enabled: !!userId },
{ queryKey: ['post', 2], queryFn: getProjectsByUser, enabled: !!userId },
]
})
For people landing here from a search: This is now supported:
const results = useQueries([
{ queryKey: ['post', 1], queryFn: getProjectsByUser, enabled: !!userId },
{ queryKey: ['post', 2], queryFn: getProjectsByUser, enabled: !!userId },
])
See https://react-query.tanstack.com/reference/useQueries#_top
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With