[英]Fetch using cached data when no internet connection - Javascript - React
我有一個Web應用程序,當沒有Internet連接時需要使用緩存的數據。 現在,我可以使用catch塊中的第二個訪存調用使其運行良好,但是我覺得這不是正確的方法。
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是避免任何問題的簡單條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.