Axios Cheat Sheet for ReactJS: Your Guide to Efficient API Calls

Axios Cheat Sheet for ReactJS

Axios is a popular JavaScript library used for making HTTP requests, whether from Node.js or through XMLHttpRequests in the browser. It is widely utilized in React applications for managing API calls effectively.

Key Concepts

  • Promise-based: Axios leverages promises, simplifying the handling of asynchronous requests.
  • HTTP Methods: It supports all common HTTP methods including GET, POST, PUT, and DELETE.
  • Interceptors: Axios enables you to intercept requests or responses prior to them being processed by then or catch.
  • Cancel Requests: You can cancel a request that is currently in progress.
  • Transforming Requests and Responses: Modify requests and responses before they are sent or received.

Installation

To add Axios to your React project, install it via npm:

npm install axios

Basic Usage

Making a GET Request

Here’s how to perform a simple GET request:

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

Making a POST Request

To send data to a server, utilize the POST method:

axios.post('https://api.example.com/data', {
    name: 'John',
    age: 30
  })
  .then(response => {
    console.log('Data saved:', response.data);
  })
  .catch(error => {
    console.error('Error saving data:', error);
  });

Configuring Requests

Customize your requests with headers, timeouts, and more:

const config = {
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 1000, // milliseconds
};

axios.get('https://api.example.com/data', config)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Using Interceptors

Interceptors can globally handle requests or responses:

axios.interceptors.request.use(config => {
  console.log('Request sent:', config);
  return config;
}, error => {
  return Promise.reject(error);
});

axios.interceptors.response.use(response => {
  console.log('Response received:', response);
  return response;
}, error => {
  return Promise.reject(error);
});

Canceling Requests

To cancel requests, employ the CancelToken:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('https://api.example.com/data', {
  cancelToken: new CancelToken(function executor(c) {
    cancel = c;
  })
}).catch(thrown => {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled:', thrown.message);
  } else {
    console.error('Error:', thrown);
  }
});

// Call cancel() to cancel the request
// cancel('Operation canceled by the user.');

Conclusion

Axios is a robust and flexible library for making HTTP requests in React applications. By mastering its core features and syntax, developers can efficiently manage data fetching and API interactions within their projects.