10

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?

Ever Dev
  • 1,882
  • 2
  • 14
  • 34

1 Answers1

17

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

TkDodo
  • 20,449
  • 3
  • 50
  • 65