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:
- An existing React project
- To install Axios with npm/yarn
- 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[]) => PromiseNow 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) =>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.