简体   繁体   English

反应查询:如果出现错误,不要在间隔内重新获取

[英]react-query: don't refetch on an interval if there is an error

I'm refetching an API on an interval, but I want to stop it if there is an error.我每隔一段时间重新获取一个 API,但如果出现错误,我想停止它。

  const { status, data, error, isFetching } = useQuery(
    'todos',
    // only refetch if there is no error
    async () => {
      const res = await axios.get('/api/data')
      return res.data
    },
    {
      refetchInterval: intervalMs,
    }
  )

I could probably store the status.isError on a state variable and then use that with enabled but it seems a bit clunky.我可能可以将status.isError存储在一个状态变量上,然后在enabled使用它,但它看起来有点笨拙。 I couldn't find anything helpful going through the documentation.我在文档中找不到任何有用的东西。

The best way is indeed to do it via local state, but you don't need to disable the query if you don't want to - just setting the refetchInterval back to 0 might also be enough:最好的方法确实是通过本地状态来做,但如果你不想,你不需要禁用查询 - 只需将refetchInterval设置回 0 也可能就足够了:

const [refetchInterval, setRefetchInterval] = useState(intervalMs)

useQuery(
  key,
  queryFn,
  {
    refetchInterval,
    onError: () => setRefetchInterval(0)
  }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM