Axios middleware to use in all instances of axios

Shakil Ahmed picture Shakil Ahmed · Nov 12, 2018 · Viewed 10.2k times · Source

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?

Answer

Fazal Rasel picture Fazal Rasel · Nov 12, 2018

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';