reactjsreact-querytanstackreact-querytanstack

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

Solution

  • You can just fallback to an empty array that you pass to useQueries if you have no users:

    function App({ users }) {
       const userQueries = useQueries(
         users?.map(user => {
           return {
             queryKey: ['user', user.id],
             queryFn: () => fetchUserById(user.id),
           }
         }) ?? []
       )
     }