While working on a system that uses frequent AJAX requests, and updates document.body.style.cursor
before each fetch()
and within finally()
, I created this wrapper to eliminate repetition…
const originalFetch = fetch;
fetch = (url, options) => {
document.body.style.cursor = 'progress'
const promise = originalFetch(url, options).catch(error => {
console.error(error)
}).finally(() => {
document.body.style.cursor = 'auto'
})
return promise
}
Usage
fetch(url).then(response => {
if (response.ok) return response.text()
throw new Error(`Response status: ${response.status}`)
}).then(text => {
// do something
})
Before creating the wrapper our fetch()
calls looked more like…
document.body.style.cursor = 'progress'
fetch(url).then((response) => {
if (!response.ok) {
throw new Error(`Response status: ${response.status}`)
}
return response.text()
}).then((text) => {
// do something
}).catch((error) => {
console.error(error)
}).finally(() => {
document.body.style.cursor = 'auto'
})
Every… single… place… fetch()
was being used 😒
Noticed this post sitting in my drafts… not sure why it was not published it, so here it is (better late than never I guess)
Pingback: Automatically Adding Default Headers to ALL Fetch (AJAX) Requests | Robert Mullaney