1

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;
jacobcan118
  • 7,797
  • 12
  • 50
  • 95

1 Answers1

7

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.

TkDodo
  • 20,449
  • 3
  • 50
  • 65
  • I though enabled parameter only to determine if query should run after first time component render..it doesn't apply the situation like once component already render but not the case that useState variable change after component render – jacobcan118 Jun 25 '21 at 18:58
  • 1
    no, that's not the case. enabled can enable or disable a query at will. – TkDodo Jun 26 '21 at 05:50