Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabled option for useQueries

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
       }
     })
   )
 }
like image 727
Austin Avatar asked Dec 18 '25 08:12

Austin


1 Answers

Update

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 },
    ]
  })

Original Answer (for React Query 3)

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

like image 145
Jonathan Avatar answered Dec 19 '25 23:12

Jonathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!