2

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;
1

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
no, that's not the case. enabled can enable or disable a query at will.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.