Axios in React – A Comprehensive Guide

Published on Oct 08,2024 38 Views

Sunita Mallick
Experienced tech content writer passionate about creating clear and helpful content for... Experienced tech content writer passionate about creating clear and helpful content for learners. In my free time, I love exploring the latest technology.

Generally, the HTTP protocol is used for backend communication in React. The XML HTTP request and Fetch API are helpful, but Axios further simplifies the process. You can send asynchronous HTTP requests to REST endpoints for CRUD operations using this library. Therefore, the Axios library is popular among Github developers.

In several React applications, Axios retrieves data from APIs, submits form data, and manages other HTTP-based interactions. Axios is compatible with several web browsers and Node.js, allowing you to use it in various environments. Here, we give you a comprehensive guide to understanding Axios in React.

Steps to Create a React Application

When you build web applications with React, Axios handles HTTP requests. React developers use Axios for various tasks, from fetching data from a server to sending new information.

Before using Axios, let’s create a React application to integrate Axios. The following steps are needed:

  • Install Node.js and npm – Ensure that Node.js and npm are installed on your machine. You can download and install them from the official Node.js website.
  • Create a New React Project – Open your terminal and run npx create-react-app axios-demo. This command creates a new React project named axios-demo. 
  • Navigate to the project directory – Go to the project directory using the command cd axios-demo.
  • Start the React Application – Run npm start to start your React development server.

Now, your application will start running on http://localhost:3000.

At this point, you can integrate Axios and use HTTP requests.

Need of Axios in React

The native Javascript application, Fetch API, also handles HTTP requests. However, it has several limitations, such as:

  • No built-in support for request cancellation
  • Cannot handle timeout errors

Axios, on the other hand, offers the following advantages:

  • Clear and simple syntax for HTTP requests
  • Efficient intercepting and handling of requests and responses
  • Automatic JSON data conversion 
  • Request cancellation
  • Timeout configuration 

Thus, React developers use Axios to create clean and easily manageable code.

GET Request with Axios

Data fetching is one of the most basic operations for any API. Axios uses intuitive syntax with the same name as the HTTP GET request. You should begin by installing Axios in the React project using the command npm install axios. Next, you can use the GET request.

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

const GetRequestExample = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      <h2>Fetched Data</h2>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  );
};

Here, the useEffect hook runs the GET request once the component mounts. The data fetched is stored in a state and rendered as a list.

POST Request with Axios

The GET request fetches data, but the POST request posts the data to a server. This is useful for applications that work with forms and get user data. A simple POST request can be used in Axios.

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

const PostRequestExample = () => {
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');

  const handleSubmit = () => {
    axios.post('https://jsonplaceholder.typicode.com/posts', {
      title,
      body,
      userId: 1
    })
    .then(response => {
      console.log('Data submitted successfully:', response.data);
    })
    .catch(error => {
      console.error('Error submitting data:', error);
    });
  };

  return (
    <div>
      <h2>Submit Data</h2>
      <input 
        type="text" 
        placeholder="Title" 
        value={title} 
        onChange={(e) => setTitle(e.target.value)} 
      />
      <textarea 
        placeholder="Body" 
        value={body} 
        onChange={(e) => setBody(e.target.value)} 
      />
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
};

Here, state variables catch user inputs, and they are sent to the server using a POST request when the user clicks the Submit button.

DELETE Request With Axios

Data that is received may need to be deleted, and Axois DELETE requests can handle that smoothly. 

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

const DeleteRequestExample = () => {
  const [message, setMessage] = useState('');

  const handleDelete = (id) => {
    axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`)
      .then(() => {
        setMessage('Item deleted successfully');
      })
      .catch(error => {
        console.error('Error deleting item:', error);
      });
  };

  return (
    <div>
      <h2>Delete Data</h2>
      <button onClick={() => handleDelete(1)}>Delete Item</button>
      <p>{message}</p>
    </div>
  );
};

 

Here, an item corresponding to a specific ID is deleted from the API, and the user receives a confirmation message after deleting the data.

Response Objects in Axios

When you use Axios to send a request, the server sends a response object back. This response object has the following properties:

  • Data: The server sends the data in payload form, which is returned in JSON form. It is parsed back into a JavaScript object, which you will receive. 
  • Status: The server sends the HTTP code (for example, 200 for a successful request).
  • StatusText: The server returns the HTTP status message.
  • Header: The server sends different headers.
  • Config: Original request configuration.

Here is a breakdown that allows you to handle multiple aspects of the response. You can have better control over your data by handling different parts of the data returned by the server:

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    console.log(response.data); // Accessing the data
    console.log(response.status); // Status code
    console.log(response.headers); // Response headers
    console.log(response.config); // Request configuration
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  }); 

Error Object

Axios excels in handling errors. The error object contains all the details, such as:

  • Message: The error message
  • Response: Includes HTTP response status, headers, and available data
  • Request: Request that triggered the error
  • Config: Configuration object used for the request

If you want to send meaningful feedback to the user for errors, you can do so with the following code:

axios.get('https://jsonplaceholder.typicode.com/invalid-url')
  .catch(error => {
    if (error.response) {
      // The request was made, and the server responded with a status code outside 2xx
      console.error('Data:', error.response.data);
      console.error('Status:', error.response.status);
      console.error('Headers:', error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      console.error('Request:', error.request);
    } else {
      // Something else happened while setting up the request
      console.error('Error:', error.message);
    }
  });

Features of Axios Library

The Axios library is preferred because of the following features:

  • Axios converts response data to JSON automatically. 
  • Interception allows you to modify requests before they are sent. 
  • Interception lets you handle responses globally. 
  • Enables you to cancel requests using tokens. 
  • You can timeout a request time. 
  • Axios runs on older browsers where Fetch isn’t supported. 
  • Set custom headers for requests. 
  • Use timeout configuration.
  • Events track the progress of a request. 
  • Cancel requests that are taking too long.

Shorthand Methods in Axios:

Axios offers several shorthand methods, such as:

  • axios.request(config)
  • axios.get(url, config)
  • axios.delete(url, config)
  • axios.head(url, config)
  • axios.options(url, config)
  • axios.post(url, data, config)
  • axios.put(url, data, config)
  • axios.patch(url, data, config)

Conclusion

Axios is the most flexible library for making HTTP requests in React. Therefore, it’s a go-to solution among developers because of its features and friendly syntax. Whether you send a simple GET request or need more complicated features like interceptors and canceling requests, Axios has your back. The React JS certification course provides the best foundation for creating React applications. You can add cleaner, more maintainable React code for scalable solutions. 

FAQs

What is Axios used for in React?

Axios is used in React to make HTTP requests to APIs for data sending or receiving. It simplifies handling asynchronous operations. Within Reach components, you can easily fetch data from a server or send data to a server. Axios also provides automatic JSON parsing, request cancellation, and error handling.

Why is Axios better than Fetch?

Axios is often considered better than the Fetch API for the following reasons:

  • Automatic JSON Handling
  • Interceptors functioning
  • Error handling
  • Built-in support for timeouts
  • Request cancellation

What is Axios in npm?

Axios in the npm package provides a promise-based HTTP client for JavaScript. It can be installed using npm install axios. You can use Axios in both client-side (like React) and server-side applications (like Node.js) to handle HTTP requests. 

What is Axios?

Axios is a promise-based HTTP client for JavaScript. It simplifies making HTTP requests. It can be used in browsers and Node.js environments.

Upcoming Batches For React JS Training Course Online
Course NameDateDetails
React JS Training Course Online

Class Starts on 30th November,2024

30th November

SAT&SUN (Weekend Batch)
View Details
React JS Training Course Online

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Axios in React – A Comprehensive Guide

edureka.co