Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call useQuery hook conditionally?

Because of the Rules of Hooks, one shouldn't call hooks conditionally. So how does one fetch data conditionally using useQuery? For example, let's say I want to fetch data inside a functional component, but only if someState === someValue? i.e I want to avoid calling useQuery() before any conditions because fetching data at these time doesn't make sense.

like image 393
M. M Avatar asked Apr 28 '20 02:04

M. M


People also ask

Can we call hooks conditionally?

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders.

Why are hooks not conditionally?

Hook functions should only be called in function-based components and in custom hooks. Hook functions should not be called conditionally. This means they should not be called in if/else blocks, loops, or nested functions. This ensures that for any component, the same hooks are invoked in the same order on every render.

What is useLazyQuery?

The useLazyQuery hook is perfect for executing queries in response to events besides component rendering. Unlike with useQuery , when you call useLazyQuery , it does not immediately execute its associated query.


2 Answers

In apollo's documentation, it shows that there's a skip option you can add: useQuery(query,{skip:someState===someValue})

Otherwise, you can also useLazyQuery if you want to have a query that you run when you desire it to be run rather than immediately.

like image 200
Zachary Haber Avatar answered Oct 29 '22 21:10

Zachary Haber


You can also use the enabled property of useQuery options for the conditional queries.

 // 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,
  }
 )
like image 25
Aj Sharma Avatar answered Oct 29 '22 20:10

Aj Sharma