0

I want to use the result of a react-query v3 useQuery statement to possibly stop refetching, depending on the result. Therefore I'd use the response data object in the QueryOptions to determine the enabled value:

const { isLoading, data } = useQuery(
  "data-querykey-" + id,
  () => api.getData({ id }),
  {
    enabled: data?.state !== "finished",
    refetchInterval: 3000,
  }
);

But this leads to the errors

  • 'data' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. ts(7022)
  • Block-scoped variable 'data' used before its declaration. ts(2448)

How can I use the result of useQuery to affect the QueryOptions? Or how to achieve the desired behavior in another way?

cachius
  • 1,743
  • 1
  • 8
  • 21

2 Answers2

1

Use a state to store if the query should be enabled and update that state accordingly:

const [enabled, setEnabled] = useState(true);
const { isLoading, data } = useQuery(/* ... */, {enabled});

const state = data?.state;
useEffect(() => {
    if (state === 'finished') setEnabled(false);
}, [state]);
trixn
  • 15,761
  • 2
  • 38
  • 55
1

The idiomatic solution for this would be to use refetchInterval as a function, instead of disabling the query:

useQuery(
  "data-querykey-" + id,
  () => api.getData({ id }),
  {
    refetchInterval: (data) => data?.state === "finished" ? false : 3000,
  }
);
TkDodo
  • 20,449
  • 3
  • 50
  • 65