在没有互联网连接的情况下使用缓存数据获取-Javascript-React



我有一个网络应用程序,当没有互联网连接时,它需要使用缓存的数据。我现在在catch块内使用第二个fetch调用可以很好地工作,但我觉得这不是正确的方法。

fetch(api)
.then(resp => resp.json())
.then(json => {
this.setState({ 
result: json.Results,
})
})
.catch(e => {
const options = {
cache: "force-cache"
}
fetch(api, options)
.then(resp => resp.json())
.then(json => {
console.log(`failed to fetch --- using cached data`)
this.setState({ 
result: json.Results,
})
})
.catch(e => {
console.error("Insufficient data")
})
})

有更好的方法吗?

检查navigator.onLine是避免任何问题的简单条件。

https://davidwalsh.name/detecting-online

最新更新