I'm using axios in my react app using import axios from 'axios
in many of my scripts. I want to use sort of a middleware that is invoked for all axios calls/errors. How do I approach this?
As per the documentation - You need to create a file i.e
// api-client.js
import axios from 'axios';
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
console.log(config);
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
export default axios;
Then from your container or controller, import above file:
// Home.js
import apiClient from './api-client.js';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With