Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-query: How to avoid triggering function call if query is empty?

I am using react-query to call an API. The call works well and is performed each time a query value is updated in an input field.
Unfortunately, it also triggers an API call even when the query is empty.

For example, when the user loads the app, the input (and hence query) will be blank.

How to trigger API calls only when there is a query?

Code

// API call
export async function myQuery(query) {
  try {
    const res = await ax.get("myapiurl", {
      params: { query },
    });
    return res.data;
  } catch {
    return null;
  }
}

// react-query
const { status, data } = useQuery(
  ["myquery", { query }],
  () => myQuery(query)
);
like image 670
DoneDeal0 Avatar asked Jun 12 '26 00:06

DoneDeal0


2 Answers

There is an enabled flag in react-query for this exact use case.

Usage example

const { status, data } = useQuery(
  ["myquery", { query }],
  () => myQuery(query).
  { enabled: !!query }
);

Docs for reference

like image 109
Abhimanyu Avatar answered Jun 14 '26 14:06

Abhimanyu


You can achieve that with a simple if sentence:

// apicall
export async function myQuery(query) {
  try {
    const res = await ax.get("myapiurl", {
      params: { query },
    });
    return res.data;
  } catch {
    return null;
  }
}

// react-query
  const { status, data } = useQuery(
    ["myquery", { query }],
    () => {
      if (query) {
        return myQuery(query)
      }
  );
like image 21
Sagi Rika Avatar answered Jun 14 '26 14:06

Sagi Rika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!