Using Axios Instance with Interceptors in Redux Toolkit Query (RTK Query)
Tags: redux, rtk, react, axios
Published: 2023-10-11 21:18:16

In this blog post, we'll walk through the process of setting up a Redux store that integrates a custom Axios instance with request and response interceptors, in addition to [Redux Toolkit Query (RTK Query)](https://redux-toolkit.js.org/introduction/getting-started). This comprehensive setup allows you to manage the state of your React application while efficiently handling API requests and responses.

**Prerequisites**

Before we start, make sure you have the following prerequisites in place:

1. A React application set up and ready to integrate [Redux](https://redux-toolkit.js.org/introduction/getting-started).
2. [Axios](https://axios-http.com/docs/intro) installed in your project. You can install Axios via npm or yarn:

```
npm install axios
# or
yarn add axios
```
**Creating a Custom Axios Instance**

First, let's create a custom [Axios instance](https://axios-http.com/docs/instance) with request and response [interceptors](https://axios-http.com/docs/interceptors). This will give you the flexibility to modify requests and responses globally:

```
// axiosInstance.js

import axios from 'axios';

const axiosInstance = axios.create({
  baseURL: 'https://api.example.com', // Replace with your API base URL
  headers: {
    'Content-Type': 'application/json',
    // Add any other headers or configurations you need
  },
});

// Add a request interceptor
axiosInstance.interceptors.request.use(
  (config) => {
    // You can modify the request config here, e.g., add authentication headers
    // config.headers.Authorization = `Bearer ${getToken()}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Add a response interceptor
axiosInstance.interceptors.response.use(
  (response) => {
    // You can modify the response data here, e.g., handling pagination
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default axiosInstance;

```

In the code above:

- We've created a custom Axios instance that includes both request and response interceptors, giving you full control over the communication with your API.

**Setting up the Redux Store**

Next, let's set up the Redux store to work in conjunction with Redux Toolkit Query. Ensure you have Redux and RTK Query installed in your project:

```
npm install @reduxjs/toolkit react-redux
# or
yarn add @reduxjs/toolkit react-redux

```

Here's how you can set up your Redux store with RTK Query:

```
// store.js

import { configureStore } from '@reduxjs/toolkit';
import { api } from './api'; // Import your RTK Query API

const store = configureStore({
  reducer: {
    [api.reducerPath]: api.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(api.middleware),
});

export default store;

```
In this store setup:

- We import the **api** object generated by RTK Query.
- The API reducer and middleware are integrated into the Redux store configuration.

**Integrating RTK Query with the Custom Axios Instance**

With your Redux store in place, you can integrate RTK Query with the custom Axios instance. This is the same step we covered in the previous sections.

```
// api.js

import { createApi } from '@reduxjs/toolkit/query'
import axiosInstance from './axios'

const axiosBaseQuery =
  ({ baseUrl } = { baseUrl: '' }) =>
  async ({ url, method, data, params, headers }) => {
    try {
      const result = await axiosInstance({
        url: baseUrl + url,
        method,
        data,
        params,
        headers,
      })
      return { data: result.data }
    } catch (axiosError) {
      const err = axiosError
      return {
        error: {
          status: err.response?.status,
          data: err.response?.data || err.message,
        },
      }
    }
  }

const api = createApi({
  baseQuery: axiosBaseQuery({
    baseUrl: 'https://example.com',
  }),
  endpoints(build) {
    return {
      query: build.query({ query: () => ({ url: '/query', method: 'get' }) }),
      mutation: build.mutation({
        query: () => ({ url: '/mutation', method: 'post' }),
      }),
    }
  },
})
```
In this step, we're integrating RTK Query with the custom Axios instance, as explained in previous sections.

**Using the Redux Store and RTK Query**

Finally, you can use the Redux store and RTK Query in your React components to manage state and make API requests:

```
// MyComponent.js

import React from 'react';
import { useGetResourceQuery, useCreateResourceMutation } from './api'; // Import the generated hooks

function MyComponent() {
  const { data, error, isLoading } = useGetResourceQuery(1); // Replace 1 with the resource ID you want to fetch

  const [createResource] = useCreateResourceMutation();

  // Use createResource function to create a new resource

  return (
    <div>
      {/* Render your component based on the API data and loading/error states */}
    </div>
  );
}

export default MyComponent;

```
By following these steps, you've set up a Redux store with a custom Axios instance that includes request and response interceptors. You've also integrated RTK Query for efficient state management and API communication in your React application. This combination offers control, flexibility, and convenience for managing your application's data.





That's it! You've now set up a Redux store with a custom Axios instance and integrated it with RTK Query to manage state and API requests in your React application. This approach allows you to have full control over the Axios instance and API interactions while leveraging the benefits of Redux and RTK Query for state management.


Follow Me on:
[facebook](https://www.facebook.com/prashanta.chakraborty.14)
[linkedin](https://www.linkedin.com/in/prashanta-chakraborty/)