Debug School

rakesh kumar
rakesh kumar

Posted on

Why we use Interceptor in react js

In React.js, an interceptor is typically used to intercept and modify HTTP requests or responses globally before they are sent or processed by the application. Interceptors are commonly used for tasks such as adding authorization headers, handling authentication, error handling, or logging.

The most popular library for handling HTTP requests and interceptors in React.js is Axios. Axios provides an easy way to create interceptors for manipulating requests and responses.

Here's an example of how interceptors can be used with Axios in React.js:

import React, { useEffect } from 'react';
import axios from 'axios';

const App = () => {
  useEffect(() => {
    // Request interceptor
    const requestInterceptor = axios.interceptors.request.use(
      (config) => {
        // Modify request config here (e.g., add headers, authentication tokens)
        console.log('Request Interceptor:', config);
        return config;
      },
      (error) => {
        // Handle request error here
        console.error('Request Interceptor Error:', error);
        return Promise.reject(error);
      }
    );

    // Response interceptor
    const responseInterceptor = axios.interceptors.response.use(
      (response) => {
        // Modify response data here (e.g., handle pagination, error handling)
        console.log('Response Interceptor:', response);
        return response;
      },
      (error) => {
        // Handle response error here
        console.error('Response Interceptor Error:', error);
        return Promise.reject(error);
      }
    );

    // Clean up interceptors on component unmount
    return () => {
      axios.interceptors.request.eject(requestInterceptor);
      axios.interceptors.response.eject(responseInterceptor);
    };
  }, []);

  // Example HTTP request
  const fetchData = async () => {
    try {
      const response = await axios.get('https://api.example.com/data');
      console.log('Data:', response.data);
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <div>
      <button onClick={fetchData}>Fetch Data</button>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, we create an App component that demonstrates the usage of interceptors with Axios.

Within the useEffect hook, we define two interceptors:

Request Interceptor: The request interceptor is used to modify the request configuration before it is sent. It can be used to add headers, authentication tokens, or perform any necessary transformations on the request. The interceptor is created using axios.interceptors.request.use().

Response Interceptor: The response interceptor is used to modify the response data or handle errors globally before the response is processed by the application. It can be used for tasks such as pagination, error handling, or transforming the response data. The interceptor is created using axios.interceptors.response.use().

We also clean up the interceptors when the component is unmounted using the return statement in the useEffect hook.

The fetchData function demonstrates an example HTTP request using Axios. The interceptors defined earlier will be applied to this request, allowing modification of the request and response as configured in the interceptors.

Top comments (0)