Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put useQuery in react-query in conditionally using typescript

I am using useQuery from react-query to fetch data that I only want the query to run in some condition. How can I use it? following is my code to use useQuery

  const query = useQuery<APIResponse, Error>(
    [{query: creatGQL, variables: variables}],
    async () => {
      const result: APIResponse = await ucFetch(apiUrl, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          query: creatGQL,
          variables: variables,
        }),
      });
      return result;
    }  );
  return query;
like image 507
jacobcan118 Avatar asked Jun 03 '26 09:06

jacobcan118


1 Answers

A query can be disabled / enabled by using the enabled option. If it is false, the query will not run:

useQuery(key, queryFn, { enabled: myCondition }

the condition can be static, or driven by state / props - anything that's a boolean really.

like image 153
TkDodo Avatar answered Jun 04 '26 23:06

TkDodo



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!