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

1

13

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?

Haulage answered 2/9, 2021 at 9:17 Comment(0)
C
24

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)
        }
    }
  }
)

Chlamys answered 2/9, 2021 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.