jacobcan118
jacobcan118

Reputation: 9099

how can I call `useQuery` from react-query in conditionally

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>
  );
}

Upvotes: 4

Views: 7277

Answers (1)

TkDodo
TkDodo

Reputation: 29056

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() });

Upvotes: 3

Related Questions