How to Conditionally Fetch useQuery in React-Query

May 07, 2021

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


👋 I'm Ashik Nesin • Sr. Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP