Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch Event on document

I can't find the way to monitor fetch events globally on document.

In jQuery it was simple:

var loading = $('#loading'); //my progress bar
$(document).bind("ajaxSend", function() {
    loading.show();
}).bind("ajaxComplete", function() {
    loading.hide();
}).bind("ajaxSuccess", function() {
    loading.hide();
}).bind("ajaxError", function() {
    loading.hide();
});

But when I started using fetch API, I lost this functionality.

Which event must I listen to in order to show the loading bar before fetch and hide it after fetch? Also, I want to do this globally on document. I do NOT want to write it like:

loading.show();
fetch('...')
   .then(response => response.json())
   .then(answer => { 
        loading.hide()
   }
.....
like image 820
Vladimir Medinsky Avatar asked Feb 17 '26 04:02

Vladimir Medinsky


1 Answers

You can readily get it back:

const myFetch = (...args) => {
    loading.show();
    return fetch(...args)
        .then(result => {
            loading.hide();
            return result;
        })
        .catch(error => {
            loading.hide();
            throw error;
        });
};

Then call myFetch instead of calling fetch directly.

Or if you can assume finally exists on your platform (or polyfill it):

const myFetch = (...args) => {
    loading.show();
    return fetch(...args).finally(() => { loading.hide(); });
};

Note that the finally feature is complete will be in the ES2018 spec.

You can even wrap fetch if you want to, but I don't recommend it:

var originalFetch = fetch;
fetch = /*...one of the above, but using `originalFetch` instead of `fetch`...*/

Your code doesn't use any ES2015+ features, so those code blocks in ES5:

function myFetch() {
    loading.show();
    return fetch.apply(null, arguments)
        .then(function(result) {
            loading.hide();
            return result;
        })
        .catch(function(error) {
            loading.hide();
            throw error;
        });
}

or

function myFetch() {
    loading.show();
    return fetch.apply(null, arguments).finally(function() { loading.hide(); });
}
like image 63
T.J. Crowder Avatar answered Feb 19 '26 18:02

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!