javascript - react-query 不会停止重试获取 API
问题描述
我想通过以下方式实现这个场景react-query
:
我的组件获取一个 API,并且应该在客户端的 Internet 断开连接时尝试一次,并且如果 Internet 重新连接,则永远不会重新获取......如果重试不成功,则在 3 秒后,应该显示一个错误,并带有一个用于重试请求的按钮。
const URL = 'https://randomuser.me/api/?results=5&inc=name';
const Example = () => {
const { error, data, isLoading, refetch } = useQuery('test', () =>
fetch(URL).then(response => response.json()).then(data => data.results), {
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: 1,
retryDelay: 3000
});
if (isLoading) return <span>Loading...</span>
if (error) return <span>Error: {error.message} <button onClick={refetch}>retry</button></span>
return (
<div>
<h1>Length: {data ? console.log(data.length) : null}</h1>
<button onClick={refetch}>Refetch</button>
</div>
)
}
考虑到上面的代码,我设置refetchOnReconnect: false
在连接互联网后禁用重新获取,retry: 1
设置一次尝试并retryDelay: 3000
设置重试时间限制。
但是当我在 DevTools 中使用 Throttling -> offline 时,单击按钮后仅显示最后一个结果并且不显示错误并在 3 秒后重试按钮...
那么,有什么办法可以处理这个功能吗?
解决方案
React-query
正在使用缓存中的数据,您应该通过调用函数使查询无效以再次获取数据invalidateQueries
:
onst URL = 'https://randomuser.me/api/?results=5&inc=name'
const Example = () => {
// Get QueryClient from the context
const queryClient = useQueryClient()
const { error, data, isLoading, refetch } = useQuery(
'test',
() =>
fetch(URL)
.then(response => response.json())
.then(data => data.results),
{
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: 1,
retryDelay: 3000
}
)
const buttonClickHandler = () => queryClient.invalidateQueries('test') // <=== invalidate the cache
if (isLoading) return <span>Loading...</span>
if (error)
return (
<span>
Error: {error.message} <button onClick={refetch}>retry</button>
</span>
)
return (
<div>
<h1>Length: {data ? console.log(data.length) : null}</h1>
<button onClick={buttonClickHandler}>Refetch</button>
</div>
)
}
推荐阅读
- php - 如何在浏览器中列出 postgresql 表数据?
- matlab - 如何在 Matlab 中组合三个单元格数组以制作具有三列的矩阵/表格?
- r - 根据其他列定义轴中断而不保存数据框
- javascript - 如何在 React Native 中动态调用模块
- image - Selenium webdriver:我想点击 https://www.msn.com/en-in/weather/today 底部的“Like 1.3M”图片
- javascript - 遍历对象元素javascript
- elasticsearch - ElasticSearch可以只添加字段索引,不保存原始值,就像lucene Field.Store.NO
- bash - 通过脚本运行进程时,作业命令结果为空
- ios - SwiftUI 跳转菜单(sectionIndexTitles)
- fortran - Fortran 无法从文件中读取