Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Interceptor with reactjs not works as expected

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading