Backbencher.dev

Enable React Query API Call Based on Another Variable

Last updated on 10 Aug, 2021

We have a Query in React Query to make an API call. The call should not happen if the value of makeAPICall is false. In this case, we can make use of enabled key in Query configuration.

const queryUsers = useQuery(
  "gitUsers",
  () => {
    return fetch("https://api.github.com/search/users?q=joby&per_page=10").then(
      (res) => res.json()
    );
  },
  {    enabled: makeAPICall,  });

enabled configuration helps us to prevent unnecessary API calls. Example, if a search textbox is empty, we can prevent making a search API call with empty query string.

--- ○ ---
Joby Joseph
Web Architect