'How can I stop a react-query useQuery running on a refetchInterval when a condition is met?

I have a requirement to keep fetching data until a condition is met I can set up the fetch on an interval with the snippet below but I can't figure out how to stop the fetchData when needed. Is this possible?

const { status: answersStatus, data: answers } = useQuery(
                           ['fetchData', { context, activity, stage, country }], 
                           fetchData,
                           {refetchInterval: 2000});


Solution 1:[1]

with a local state:

const [refetchInterval, setRefetchInterval] = React.useState(2000)
const { status: answersStatus, data: answers } = useQuery(
    ['fetchData', { context, activity, stage, country }], 
    fetchData,
    {refetchInterval});

you can set the refetchInterval to false or 0 to turn it off. If you want to do it depending on the response, the onSuccess, onError or onSettled callbacks are likely the best place:

const [refetchInterval, setRefetchInterval] = React.useState(2000)
const { status: answersStatus, data: answers } = useQuery(
    ['fetchData', { context, activity, stage, country }], 
    fetchData,
    {
        refetchInterval,
        onError: () => setRefetchInterval(0)
    });

Solution 2:[2]

In the end I leveraged short-circuit evaluation so my call is now

const { data: answers } = useQuery(
    isThereSomethingToGet && [`fetchData`, { ...qmfRouteParams, context: appContext }],
    fetchData,
    {
      refetchIntervalInBackground: true,
      refetchInterval: DocusignPolling.INTERVAL,
    },
  );

When isThereSomethingToGet is falsy the function isn't called.

Solution 3:[3]

For me, it was causing infinite loop until passing function to the refetchInterval like so:

refetchInterval: data => (checkMyResponseHere(data) ? false : 2000)

P.S. react-query v.3.38.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TkDodo
Solution 2 chris loughnane
Solution 3 ??????? ?????????