Skip to content
Advertisement

How to call a specific function before and after every fetch api request and response

I want to call a function during sending a request and after receiving response with every fetch() function using Vanilla JS. I saw that jquery ajax is providing some kind of $.ajaxsetup for doing this but I want to do it with Vanilla JS. Thanks in advance.

Advertisement

Answer

fetch doesn’t have a feature like that. You could write a wrapper function though:

const myFetch = async (...args) => {
    do_before();
    const result = await fetch(...args);
    do_after();
    return result;
}

and then call that function instead of accessing fetch directly.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement