Efficient request handling and token refresh in React Js with Axios Interceptors

Tram Ho

Preamble

Most of a Front-end Developer used to use Axios to handle requests in their project. Axios interceptor is a feature of the Axios library used to process requests and responses before they are sent or received. It allows you to customize the requests and responses in the communication between your application and the API. After working with it for a while, I will show you how to configure Axios interceptor in a React project using Typesript

Use

  1. install Axios library:

or:

  1. Create an AxiosInterceptor.ts file:
  • In this file we will create 3 functions to configure the request before sending and returning the response:
  • Config requests:

  • Config response success:

  • Config response error:

  • Then we will use the functions defined above with request.use and response.use methods to add interceptors to Axios.:

  1. Put all the newly created functions into one function to export using:

  1. Using the AxiosInterceptor.ts file we just created above: Here I am not initializing an instance using axios.create() but I still use the default axios and just override it, so I will use the function just created in the file index.tsx:

Finish

This is the way I often use to configure requests and refresh tokens in my project. There are also other ways to deal with the Axios library, you can learn more to have the right ways for your project.

References

https://axios-http.com/

Share the news now

Source : Viblo