Published on

How to Conditionally Fetch useQuery in React-Query

Authors

useQuery in react-query package is used to fetch data from api. By default, it gets triggered when the components gets mounted. However, sometime we need to conditionally query it.

It can be done by using it's enabled option. Here's how to do it.

const isAutoFetching = false;
const { isLoading, error, data } = useQuery(
  'repoData',
  () =>
    fetch('https://api.github.com/repos/tannerlinsley/react-query').then(res =>
      res.json()
    ),
  { enabled: isAutoFetching }
);

Reference