Display spinner during AJAX call when using fetch API
ajax, fetch-api, javascript
Solution
There you go, I think the code is pretty much self-explanatory:
// Store a copy of the fetch function
var _oldFetch = fetch;
// Create our new version of the fetch function
window.fetch = function(){
// Create hooks
var fetchStart = new Event( 'fetchStart', { 'view': document, 'bubbles': true, 'cancelable': false } );
var fetchEnd = new Event( 'fetchEnd', { 'view': document, 'bubbles': true, 'cancelable': false } );
// Pass the supplied arguments to the real fetch function
var fetchCall = _oldFetch.apply(this, arguments);
// Trigger the fetchStart event
document.dispatchEvent(fetchStart);
fetchCall.then(function(){
// Trigger the fetchEnd event
document.dispatchEvent(fetchEnd);
}).catch(function(){
// Trigger the fetchEnd event
document.dispatchEvent(fetchEnd);
});
return fetchCall;
};
document.addEventListener('fetchStart', function() {
console.log("Show spinner");
});
document.addEventListener('fetchEnd', function() {
console.log("Hide spinner");
});
Here's a live example: https://jsfiddle.net/4fxfcp7g/4/
Problem
In my project I am migrating to React and so not loading JQuery. Since I don't have JQuery anymore, for AJAX calls I am using fetch. With JQuery I can hook the start and end of AJAX calls so it's very easy to change the cursor to a spinner. I can't find similar hooks in fetch. Is there a way to do this other than changing it in each individual AJAX call? Lots of Googling just kept finding answers about... JQuery.