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