'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.
Solution 1:[1]
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.
Solution 2:[2]
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,
}
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Joe Lafiosca |
Solution 2 | Aj Sharma |