0

I have logic to stop the polling from within the react query

refetchInterval: (data) => data?.status_code === 'SUCCESS' ? false : 5000

But how to stop the polling in some other component when a Button is clicked. I tried this but somehow the polling still continues.

queryClient.cancelQueries({ queryKey: ['runStatus'] })

Dhruv Pandey
  • 482
  • 6
  • 18

1 Answers1

2

I might be wrong, but I don't think you can do it through queryClient methods programatically. cancelQueries just cancels currently running requests, but it does not disable future requests.

What you can do if to have some sort of shared state somewhere, e.g. in React Context or any other state library or other way that you like. And then you just set an enabled react-query flag there and use it for your query, in pseudocode it would look like that:

// for example this is a root component that renders both Button and your fetching component

const [queryEnabled, setQueryEnabled] = React.useState(true)

// ...

<Button onClick={() => setQueryEnabled(status => !status)} />

<FetchingComponent queryEnabled={queryEnabled} />


// and inside of FetchingComponent:

useQuery({ 
  enabled: props.queryEnabled,
  // your other options
})

You can of course pass refetchInterval or any other option instead of enabled if you wish.

Danila
  • 15,606
  • 2
  • 35
  • 67