没有互联网连接时使用缓存的数据获取-Javascript-React

时间:2018-12-03 14:48:30

标签: javascript caching fetch

我有一个Web应用程序,当没有Internet连接时需要使用缓存的数据。现在,我可以在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")
        })
    })

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

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

https://davidwalsh.name/detecting-online