reactjsreact-apolloreact-queryreact-apollo-hooks

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

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