【问题标题】:React Query: Can I use React Query for polling until I get certain data?React Query:在获得某些数据之前,我可以使用 React Query 进行轮询吗?
【发布时间】:2021-10-31 18:18:06
【问题描述】:

我想实现长轮询,直到我从 API 获得某些数据。

例如,假设我们有一个返回进程进度的 API。 我想调用那个 API,直到这个过程完成。

是否可行,如果可行,我该如何实施?

【问题讨论】:

    标签: reactjs long-polling react-query


    【解决方案1】:

    我们为该用例准备了一个 PR,一旦我们发货,您就可以这样做:

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

    api 尚未最终确定,实际上我会很感激一些输入 :)


    在那之前,您需要使用本地状态来处理这个问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2022-08-04
      • 2019-01-05
      • 2021-09-17
      相关资源
      最近更新 更多