Skip to content

Instantly share code, notes, and snippets.

@andon
Created January 9, 2018 23:04
Show Gist options
  • Save andon/476c3d7807c48295effa2f2bfb848517 to your computer and use it in GitHub Desktop.
Save andon/476c3d7807c48295effa2f2bfb848517 to your computer and use it in GitHub Desktop.
Fetch with client revalidation. On failure performs another fetch without client revalidation, so that you get cached result if available.
const doFetch = (url, opts = {}) => {
const headers = new Headers()
headers.append('Cache-Control', 'max-age=0')
if (opts.headers) {
for (const header of opts.headers) {
headers.append(header[0], header[1])
}
}
return new Promise((resolve, reject) => {
fetch(url, {
...opts,
headers,
})
.then(response => {
if (response.ok) {
resolve(response)
}
throw new Error('Network response was not ok.')
})
.catch(() => {
fetch(url, opts)
.then(resolve)
.catch(reject)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment