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)
);
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
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)
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With