Complete Setup of Axios Wrappers in React TypeScript


What is Axios?

Axios is an HTTP client library based on the XMLHttpRequests service that allows you to make requests to a given endpoint similar to the Fetch API.

The advantage of Axios over Fetch API

  • supports older browsers
  • and has a URL in the request object.
  • has a way to abort a request
  • has a way to set a response timeout
  • supports upload progress
  • has built-in support for download progress.
  • performs automatic JSON data transformation.

Installation steps for Axios into our React application

To install Axios, we run the following command:npm install axios

Using Axios with React is a very simple process. You need three things:

  1. An existing React project
  2. To install Axios with npm/yarn
  3. An API endpoint for making requests

If you have an existing React project, you just need to install Axios with npm (or any other package manager):

Axios Wrapper Class APIService 

To start, we create an APIService class. This class contains a private property axiosClient which is of type Axios. It also has a constructor method that will initialize an Axios client by axios.create() method that takes in API_CONFIG parameter. This client is set up upon initialization of the class. From here, we created some API methods for any instance of the class to call (get, post, put, patch, and delete), which in turn maps to Axios requests.

Axios interceptors are the default configurations that are added automatically to every request or response that a user receives. It is useful to check the response status code for every response that is received. Interceptors are methods that are triggered before making the request. There are two types of interceptors:

  • request interceptors: — It allows you to write or execute a piece of your code before the request gets sent.
  • response interceptors: — It allows you to write or execute a piece of your code before the response reaches the calling end. 
  • success handler is a method that will execute when we receive a response in configured interceptor.
  • error handler is a method that will execute when we don’t receive any response and interceptors throw an error then the error handler will get executed.

One of the main benefits of creating this wrapper is that we create a sort of interface between Axios and the rest of our app. This makes it easy for instance, to swap axios out for another package, should we choose to do so in the future, without it breaking our app.

It also allows us to keep our code DRY if we have to work with multiple different APIs that each require their own axios instances.

import axios, { Axios, AxiosError, AxiosRequestConfig, AxiosResponse, } from “axios”; const API_CONFIG: AxiosRequestConfig = { baseURL: “https://63b996074482143a3f15afbc.mockapi.io/”, responseType: “json”, }; const DEFAULT_VALUE_FOR_ERROR_RESPONSE = { data: { message: “” }, status: 0, }; export class APIService { axiosClient: Axios; static instance: APIService; constructor() { this.axiosClient = axios.create(API_CONFIG); this.configureInterceptors(); } static getInstance = () => { if (!this.instance) { this.instance = new APIService(); } return this.instance; }; errorHandler = async (error: AxiosError) => { const { response } = error; const { data, status } = response || DEFAULT_VALUE_FOR_ERROR_RESPONSE; const message = data; return { data: null, status, statusText: message, }; }; successHandler = (response: AxiosResponse) => { const { status, statusText, headers } = response; return { data: response.data, status, statusText, headers, }; }; configureInterceptors = () => { this.axiosClient.interceptors.response.use( (response: AxiosResponse) => this.successHandler(response), (error: AxiosError) => this.errorHandler(error) ); this.axiosClient.interceptors.request.use((request) => request); }; updateAuthToken = (token: string) => { this.axiosClient.defaults.headers.common.Authorization = `${token}`; }; get = async (url: string) => { const res = await this.axiosClient .get(url) .then((response: AxiosResponse) => response); return res; }; delete = async (url: string) => { const res = await this.axiosClient .delete(url) .then((response: AxiosResponse) => response); return res; }; post = async (url: string, payload: any, config?: any) => { let res; if (config) { res = await this.axiosClient .post(url, payload, config) .then((response: AxiosResponse) => response); } else { res = await this.axiosClient .post(url, payload) .then((response: AxiosResponse) => response); } return res; }; put = async (url: string, payload: any) => { const res = await this.axiosClient .put(url, payload) .then((response: AxiosResponse) => response); return res; }; patch = async (url: string, payload: any) => { const res = await this.axiosClient .patch(url, payload) .then((response: AxiosResponse) => response); return res; }; }

api-service.ts

In the above api-service.ts file baseURL is set in APIService Class. Now it’s time to call (get, post, put, patch, and delete) API by their respective Endpoints for that we have to make a class that implements the IBaseApiHandler interface. In get() we pass endpoint all_users as a parameter, same we can also pass payload and endpoint for post() request.

get-all-users.ts

import { APIService } from “../../network/api-service”; interface IBaseApiHandler { invoke: (…args: any[]) => Promise; formatRequest?: (request: any) => any; formatResponse?: (response: any) => any; } export class GetAllUsers implements IBaseApiHandler { async invoke() { const response = await APIService.getInstance().get(“all_user”); return response; } }

Now we have to make class Api where we call all our APIs.

api.ts

import { GetAllUSers } from “./get-all-users”; export class Api { static async getAllUsers() { return new GetAllUsers().invoke(); } }

Now you need to get API data in your component so that you can use data to render on screen.

App.tsx

import React, { useEffect, useState } from “react”; import { Api } from “./service/network/api”; const App = () => { const [allUsers, setAllUsers] = useState([]); const getData = async () => { const users = await Api.getAllUsers(); setAllUsers(users?.data); }; useEffect(() => { getData(); }, []); const renderAllUsersName = () => allUsers?.map((user: any) =>
{user.name}
); return
{renderAllUsersName()}
; }; export default App;

Hope this article is helpful for you and you must have learned now how to set up Axios Wrappers in React TypeScript.

Big thanks for your precious time & please share your feedback.

Happy Coding!! Keep Learning & Keep Growing.

Latest

SENTRY integration in your React Native App for Error/Crash tracking

Sentry captures data by using an SDK within your...

Recall the concepts of useCallback.

useCallback hook is one of the best hooks offered...

Value of Comments in the code!!

During my journey of Software Development, I am always...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million...

Featured

Developing Enterprise Application in Node.js – CJS Vs ESM

Node.js is a popular runtime environment for building server-side...

Integrating your web react applications with their React Native(android and IOS) apps using QR code

Integrating a web application with Android and iOS apps...

YOLO: Bullet Paced Algorithm – popular choice for object detection in autonomous vehicles 

According to world health organization, more than 1.35 million...

Importance of Test Scalar Tool

TestScalar is quick to access, convenient to execute, easy to track. Our popular web-based test planning software lets you focus on what matters: meeting...

From Requirements to Reporting: How to Use a Test Case Management Tool to Ace Your Software Testing

The Software Testing Life Cycle (STLC) is a process that describes the stages of testing software. It includes planning, design, execution, and reporting of...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million people die every year because of vehicle accidents . Vehicle safety features started with passive safety...

LEAVE A REPLY

Please enter your comment!
Please enter your name here