Interceptor with reactjs not works as expected

Advertisements

I am trying to implement a global level preloader on api request. I just tried it with sample. but not works. how to implement the interceptor globally?

import axios from 'axios';

export default async (searchTerms) => {
  try {
    const url = `${process.env.SERVICE_URL}/get-jayachan-detais`;
    const params = JSON.stringify({
      orderInfoRequest: {
        searchType: 'MASTER TRX',
        MasterTrxnId: searchTerms.ordnum
      }
    });
    const response = await axios.post(url, params, { withCredentials: true });

    return {
      errors: [],
      response
    };
  } catch (e) {
    return {
      errors: [e]
    };
  }
};

axios.interceptors.request.use(function () {
    console.log('start preloader');
});

axios.interceptors.response.use(function () {
    console.log('stop preloader');
});

>Solution :

Return the config object in the request interceptor and the response data/err in the response interceptor:

import axios from 'axios';

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    console.log('start preloader');
    return config;
}, function (error) {
    console.error('Error: request interceptor:', error);
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    console.log('stop preloader');
    return response;
}, function (error) {
    console.error('Error: response interceptor:', error);
    return Promise.reject(error);
});

export default async (searchTerms) => {
    try {
        const url = `${process.env.SERVICE_URL}/get-jayachan-details`;
        const params = {
            orderInfoRequest: {
                searchType: 'MASTER TRX',
                MasterTrxnId: searchTerms.ordnum
            }
        };
        const response = await axios.post(url, params, { withCredentials: true });

        return {
            errors: [],
            response: response.data // Return response data
        };
    } catch (e) {
        return {
            errors: [e]
        };
    }
};

Additionally, suppose if you get error response, it will help you to troubleshoot and debug the issue well.

Leave a ReplyCancel reply