How to call useQuery hook conditionally?

React-Apollo:

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.

If you are using the suspense based hooks useSuspenseQuery and useBackgroundQuery you need to use the new skipToken import as the options, since the skip option is deprecated for these new hooks.

import { skipToken, useSuspenseQuery } from '@apollo/client';
const { data } = useSuspenseQuery(
  query,
  id ? { variables: { id } } : skipToken
);

Edit: 2 Years after the question was posted, the question tags were edited to add “react-query” which wasn’t in the original question.

React-Query

As mentioned in the other answer, you can use the enabled flag in React Query. Code example from the documentation link.

// Get the user
const { data: user } = useQuery({
  queryKey: ['user', email],
  queryFn: getUserByEmail,
})

const userId = user?.id

// Then get the user's projects
const {
  status,
  fetchStatus,
  data: projects,
} = useQuery({
  queryKey: ['projects', userId],
  queryFn: getProjectsByUser,
  // The query will not execute until the userId exists
  enabled: !!userId,
})

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)