reactjslong-pollingreact-query

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?


Solution

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