Using axios Interceptors in React Native
- Stanly Medjo
- May 14, 2024
- 2 min read
Updated: Aug 18, 2024
Interceptors are a very fun concept in axios, and they can permit you to intercept and modify requests before being sent to the server. It can be used for scenarios such as requesting new tokens or showing error messages when a request fails. In this article, we will see what interceptors are in axios and how to create a small snippet to handle interceptors in React Native.
What are interceptors in axios?
Interceptors are built mechanisms in axios that permit you to modify the request or the responses of HTTP requests. They permit you to handle your application state better. Being a native feature in axios, interceptors can be instantiated from the general axios config.
Types of interceptors
There exist two types of interceptors in axios: request and response interceptors.
Request interceptor
The request interceptor is used to intercept all requests sent by the users; you can use it to modify the outgoing request, such as adding an access token to the request header. We can see an example of the interceptor below
Â
The config passed in the callbacks contains parameters from requests, such as the headers, URL, request parameters, and request type. Changing config parameters take effect in the request, and it's important always to return the request.
Response interceptor
The response interceptor is used to handle the responses from axios requests. The response has a call back as in the request interceptor, which gives you the response details before it is sent back to the user. You can use it to check specific error codes and display custom notification errors.
Adding axios interceptors in React Native
After seeing the different interceptors and how they work, we will see how we can add axios in our React Native project, and we will write HOC to intercept all axios requests. We shall start by installing axios by running the following command.
Now we will create our HOC to handle all axios requests; in the snippet below, we add the access token when doing requests and also handle all response errors.
Ps: in a normal scenario, I use a toast to display errors when the request fails.
In the example, we used redux to get the values such as access and refresh tokens. Now that we have our snippet working, we will create or HOC, for that create a file called interceptorProvider add and the following code.
Now you will need to wrap your application with the interceptorProvider, for that add it in your application as follows.
It's important to note that you will need to modify the snippets above for it to work in your application smoothly
Conculsion
In the article we saw how to use axios interceptors in react native, and we also saw how we can include them with some little snippets on how we can include them in React Native.