skip to Main Content

I want to fire an event when there is a new network request. I have overwritten the fetch by following code,

        window.fetch = new Proxy(window.fetch, {
            apply(actualFetch, that, args) {
                const result = Reflect.apply(actualFetch, that, args);

                result.then(() => {
                    if (args.some(i => {
                        return (
                            typeof i === 'string' &&
                            (i?.includes('/example')
                        )
                    })) {
                        console.log('hello')
                    }
                });

                return result;
            }
        });

It works only when I make a new request using fetch but when I make an axios request from different script file (compiled react) it doesn’t fire any event. Any idea?

2

Answers


  1. Axios uses the XMLHttpRequest under the hood, instead of the fetch

    Login or Signup to reply.
  2. Axios uses the XMLHttpRequest api.

    You could still make it work by using interceptors in the axios library, here’s an example :

    // Intercept requests with Axios
    axios.interceptors.request.use((c) => {
        // Call your custom logic here
        console.log(c.url);
        return c;
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search