Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Query: Can I use React Query for polling until I get certain data?

I want to implement long-polling until I get certain data from an API.

For example, let's say we have an API that returns the progress of a process. And I want to call that API until the process is finished.

Is it feasible and if so, how can I implement it?

like image 877
Ever Avatar asked Dec 07 '25 03:12

Ever


1 Answers

We have a PR ready for just that use-case, once we ship it, you can do:

const query = useQuery(
  key,
  fn,
  {
    refetchInterval: (data) => !data || data.progress < 100 ? 5000 : undefined
  }
)

api is not finalized, I'd appreciate some input actually :)


until then, you'd need to handle this with local state:

const [refetchInterval, setRefetchInterval] = React.useState(5000)
const query = useQuery(
  key,
  fn,
  {
    refetchInterval,
    onSuccess: (data) => {
        if (data.progress === 100) {
          setRefetchInterval(false)
        }
    }
  }
)

like image 114
TkDodo Avatar answered Dec 08 '25 18:12

TkDodo