Monday

React common api calls with axios (typescript)

Firstly, create a component called as "request.ts"
import axios from 'axios';
import I from 'immutable';

const apiURL = axios.create({
  baseURL: process.env.MY_API_URL, // example: localhost:8080/
});

const request = function (options) {

  const onSuccess = function (response) {
    const data = response.data;

    if (data.myErrorFromApiAsSuccessStatus) {
      return myStructureError(data.myErrorFromApiAsSuccessStatus);
    }
    return I.fromJS({ data });
  };

  const onError = function (error) {
    if (error.response && error.response.data && error.response.data.myErrorFromApiAsSuccessStatus) {
      return myStructureError(error.response.data.myErrorFromApiAsSuccessStatus);
    }

    console.log(`
      url: ${options.url}
      message:  ${error.message}
      stackTrace: ${error.stack}
    `);

    return Promise.reject(error.message);
  };

  function myStructureError(myErrorFromApiAsSuccessStatus) {
    const error = (`
      url: ${options.url}
      message: ${myErrorFromApiAsSuccessStatus.message}
    `);
    console.log(error);

    return Promise.reject(error);
  }

  return apiURL(options)
    .then(onSuccess)
    .catch(onError);
};

export default request;

Use request component in your api calls as following: (api.ts)
import request from '../request';

export const getMyData = async(mydata: string) => {
  return request({
    url:  '/my-data',
    method: 'POST',
    data: {
      mydata : mydata,
    },
  });
};

No comments:

Post a Comment