Maneja #ERRORS como un campeón con #AXIOS #INTERCEPTOR, te muestro mi técnica milenaria - PT 2

3 min read 1 year ago
Published on Aug 06, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will guide you through handling errors in your React projects using Axios interceptors. You'll learn how to set up Axios to manage headers and errors effectively, allowing you to improve the reliability of your API calls. This method has been tried and tested, making it a valuable technique for web developers.

Step 1: Setting Up Axios in Your Project

To begin, ensure you have Axios installed in your React project. If you haven’t done so, follow these steps:

  1. Install Axios: Open your terminal and run the following command:

    npm install axios
    
  2. Create an Axios Instance: In your project, create a new file, say axiosInstance.js, and set up your Axios instance:

    import axios from 'axios';
    
    const axiosInstance = axios.create({
        baseURL: 'https://your-api-url.com', // replace with your API URL
        timeout: 1000, // optional timeout for requests
    });
    
    export default axiosInstance;
    
  3. Import the Axios Instance: In your components where you plan to make API calls, import the Axios instance:

    import axiosInstance from './axiosInstance';
    

Step 2: Implementing Axios Interceptors

Interceptors allow you to intercept requests or responses before they are handled by then or catch.

  1. Add a Request Interceptor: In your axiosInstance.js, add a request interceptor to include headers or perform any pre-processing:

    axiosInstance.interceptors.request.use(
        config => {
            // Add authorization token or any required headers
            config.headers['Authorization'] = 'Bearer your_token'; // replace with your token logic
            return config;
        },
        error => {
            return Promise.reject(error);
        }
    );
    
  2. Add a Response Interceptor: To handle errors globally, add a response interceptor:

    axiosInstance.interceptors.response.use(
        response => {
            return response;
        },
        error => {
            // Handle errors based on the response status
            if (error.response) {
                // Server responded with a status outside 2xx range
                console.error('Error status:', error.response.status);
                console.error('Error data:', error.response.data);
            } else {
                // No response received
                console.error('Error message:', error.message);
            }
            return Promise.reject(error);
        }
    );
    

Step 3: Using Axios in Your Components

Now that your interceptors are set up, you can use Axios to make API calls in your components.

  1. Make an API Call: Use the Axios instance in your component to fetch data:
    import React, { useEffect } from 'react';
    import axiosInstance from './axiosInstance';
    
    const MyComponent = () => {
        useEffect(() => {
            const fetchData = async () => {
                try {
                    const response = await axiosInstance.get('/data-endpoint'); // replace with your endpoint
                    console.log('Data fetched:', response.data);
                } catch (error) {
                    console.error('Error fetching data:', error);
                }
            };
    
            fetchData();
        }, []);
    
        return <div>My Component</div>;
    };
    
    export default MyComponent;
    

Conclusion

By following the steps outlined in this tutorial, you have set up Axios with interceptors to manage API requests and handle errors effectively in your React project. This technique will enhance your app's robustness and make debugging easier.

For next steps, consider exploring how to customize error handling further or implementing additional features, such as retry logic for failed requests. You can also check the provided GitHub repository for more examples and project structure.