jacobcan118
jacobcan118

Reputation: 9037

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;

Upvotes: 2

Views: 5798

Answers (1)

TkDodo
TkDodo

Reputation: 28733

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.

Upvotes: 8

Related Questions