I have 3 functions shouldCallApi return true or false that decide if useApiCall should trigger
if yes, useSecondApiCall will return some data and pass into query for useApiCall to build its query then return the response
no problem for me to call useApiCall under component level however how can I make sure useApiCall only trigger when shouldCallApi return as true?
export function shouldCallApi(): boolean {
...
}
export function useApiCall(
parameter,
shouldExecuteQuery = true
) {
const [query] = useDebounce(parameter, 350);
const {data} = useSecondApiCall(query);
const {totalNumber} = data?.number || {};
const query = useQuery<APIhCreateMutation, Error>(
[{query: apihCreateGQL, variables: {...query, count: totalNumber}}],
async () => {
const result: APIhCreateMutation= await ucFetch(apiUrl, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
query: apiCreateGQL,
variables: {...query, count: totalNumber},
}),
});
return result;
},
{refetchOnWindowFocus: false, enabled: shouldExecuteQuery, keepPreviousData: true}
);
return query;
}
export default function App() {
const query = useSelector((state) => state.query);
const {response} =useApiCall(query)
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Edit to see some magic happen!</h2>
</div>
);
}
how can I make sure useApiCall only trigger when shouldCallApi return as true?
That is what the enabled option is for, which you are already using in your example - but it is not clear to me how shouldExecuteQuery and shouldCallApi play together?
As long as enabled is false, the query will "pause". If you have no data yet, it will be in idle state. When enabled transitions from false to true, an automatic refetch will be triggered.
So really, it's just:
useQuery(queryKey, queryFn, { enabled: shouldCallApi() });
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