Category: 05. Axios

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ2jxQoVNx-WIU4Bl5mjNofE61lEyjSt_mknw&s

  • Optimize Performance

    Be mindful of the performance implications of making too many requests. Use techniques such as batching, caching, or request throttling to optimize performance.

  • Avoiding Duplicate Requests

    To avoid making duplicate requests, you can use a request queue or check if a request is already in progress before making a new one.

  • Using Interceptors Wisely

    While interceptors are powerful, use them carefully to avoid unexpected behavior in your requests or responses. Interceptors can modify requests globally, which can affect all Axios calls.

    axios.interceptors.request.use(config => {
      // Add authentication token
      config.headers['Authorization'] = 'Bearer YOUR_TOKEN';
      return config;
    }, error => {
      return Promise.reject(error);
    });
    
  • Error Handling

    Always handle errors in your Axios requests to ensure your application can gracefully handle network issues or server errors.

    axios.get('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => {
    
    console.log('Data:', response.data);
    }) .catch(error => {
    if (error.response) {
      // Server responded with a status other than 2xx
      console.error('Response Error:', error.response.status);
      console.error('Response Data:', error.response.data);
    } else if (error.request) {
      // Request was made but no response received
      console.error('Request Error:', error.request);
    } else {
      // Error setting up the request
      console.error('Error Message:', error.message);
    }
    });
  • Handling Cookies and Sessions

    Axios doesn’t handle cookies directly, but you can configure it to work with cookies by using withCredentials if you’re making cross-origin requests.

    axios.get('https://example.com/data', {
      withCredentials: true // Send cookies with request
    })
      .then(response => {
    
    console.log('Data:', response.data);
    }) .catch(error => {
    console.error('Error:', error);
    });
  • Retrying Failed Requests

    For handling transient errors, you might want to retry failed requests. This is not built into Axios by default, but you can achieve it using libraries like axios-retry.

    First, install the axios-retry package:

    npm install axios-retry
    

    Then configure it with your Axios instance:

    const axiosRetry = require('axios-retry');
    
    axiosRetry(axios, { retries: 3 });
    
    axios.get('https://jsonplaceholder.typicode.com/posts/1')
      .then(response => {
    
    console.log('Data:', response.data);
    }) .catch(error => {
    console.error('Error:', error);
    });
  • Setting Up Global Defaults

    You can set up global defaults for Axios that apply to all requests. This can include setting default headers, base URLs, and timeouts.

    axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
    axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';
    axios.defaults.timeout = 5000;
    
    // Making a request with global defaults
    axios.get('/posts')
      .then(response => {
    
    console.log('Data:', response.data);
    });
  • Transforming Requests and Responses

    You can modify the request or response data by transforming it. This is useful for modifying data before sending it or after receiving it.

    axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'foo',
      body: 'bar',
      userId: 1
    }, {
      transformRequest: [(data, headers) => {
    
    // Modify request data before sending it
    return JSON.stringify(data);
    }], transformResponse: [data => {
    // Modify response data before passing it to then
    return JSON.parse(data);
    }] }) .then(response => {
    console.log('Transformed Data:', response.data);
    }) .catch(error => {
    console.error('Error:', error);
    });
  • Creating and Using Custom Instances

    You can create custom Axios instances with different configurations for different parts of your application. This can help manage different base URLs, headers, and other settings.

    // Create an instance with a custom configuration
    const apiClient = axios.create({
      baseURL: 'https://jsonplaceholder.typicode.com',
      timeout: 1000,
      headers: {'Authorization': 'Bearer YOUR_TOKEN'}
    });
    
    // Use the custom instance to make requests
    apiClient.get('/posts')
      .then(response => {
    
    console.log('Data:', response.data);
    }) .catch(error => {
    console.error('Error:', error);
    });
  • Handling Concurrent Requests

    Axios allows you to handle multiple concurrent requests with ease using axios.all and axios.spread. This can be particularly useful for making multiple requests simultaneously and handling their results once all are complete.

    const requestOne = axios.get('https://jsonplaceholder.typicode.com/posts/1');
    const requestTwo = axios.get('https://jsonplaceholder.typicode.com/posts/2');
    
    axios.all([requestOne, requestTwo])
      .then(axios.spread((responseOne, responseTwo) => {
    
    console.log('Post 1:', responseOne.data);
    console.log('Post 2:', responseTwo.data);
    })) .catch(error => {
    console.error('Error:', error);
    });