How to create a global Handler with React & AXIOS?

Viewed 1798

I'm using ReactJs & AXIOS in this project and i want to make a global error handler without passing by everywhere the request to add catch to it . I've a service gathering all the requests and I'm creating a new instance of it and use it

import Axios from 'axios';
import { getSiteId } from '../helpers';

export class BaseService {
  baseRoute;
  promise;
  constructor() {
    let siteUrl = (process.env && process.env.REACT_APP_API_URL) || '';
    this.baseRoute = `${siteUrl}/api/v1`;

  }

  async create(item) {
    return await Axios.post(`${this.generateURL()}/`, item, {
      ...this.configuration,
    })
      .catch(error => {
        return this.errors(error);
      });

  }
  async update(item, id) {
    return await Axios.patch(`${this.generateURL(id)}`, item, {
      ...this.configuration,
    });
  }
  async filter(query) {
    return await Axios.get(`${this.generateURL()}`, {
      ...this.configuration,
      params: query,
    });

}

creating a new instance like so

let service= serviceFactory.getInstance();

Then access any function

how to do a global handler adding .catch to every request and render component for example modal from global place , and not to pass to every place i use the functions at

2 Answers

You could use Axios.create() method. An example from the official documentation.

export const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

Now you can export it to use anywhere like this.

import { instance } from './service'

OR with Common JS

const { instance } = require('./service')
Related