A Comprehensive Comparison of HTTP Request Methods in React: Axios vs. Fetch

Axios vs Fetch

When building web applications, performing HTTP requests is an integral part of the development process. React, being a popular JavaScript library for building user interfaces, often requires developers to interact with APIs and fetch data. Two commonly used approaches for making HTTP requests in React are Axios and the Fetch API. In this blog, we will undertake an in-depth exploration of these two methods for various HTTP request types: GET, POST, PUT, PATCH, and DELETE. By the end, you'll have a clear understanding of when to choose Axios or the Fetch API for your React project.

Axios: The Versatile HTTP Library

Axios is a widely embraced JavaScript library renowned for its simplicity, ease of use, and robust browser support, making it a preferred choice among React developers.

Performing a GET Request with Axios

To execute a GET request in a React component using Axios:

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

function App() {
  const [data, setData] = useState([]);

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

  return (
    <div>
      {/* Display data here */}
    </div>
  );
}

export default App;

This code showcases how to use Axios in a React component to fetch data when the component mounts. The fetched data is then used to update the component's state.

Sending a POST Request with Axios

To make a POST request with Axios and handle user input:

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

function App() {
  const [postData, setPostData] = useState({ title: '', body: '' });

  const handleSubmit = () => {
    axios.post('https://jsonplaceholder.typicode.com/posts', postData)
      .then((response) => {
        console.log('Post created:', response.data);
      })
      .catch((error) => {
        console.error(error);
      });
  };

  return (
    <div>
      {/* Create a form for user input */}
      <form>
        <input
          type="text"
          placeholder="Title"
          onChange={(e) => setPostData({ ...postData, title: e.target.value })}
        />
        <textarea
          placeholder="Body"
          onChange={(e) => setPostData({ ...postData, body: e.target.value })}
        />
        <button type="button" onClick={handleSubmit}>
          Create Post
        </button>
      </form>
    </div>
  );
}

export default App;

In this example, a form collects user input, and when the "Create Post" button is clicked, Axios sends a POST request.

Handling PUT and PATCH Requests with Axios

Axios also facilitates PUT and PATCH requests:

PUT Request:

axios.put('https://jsonplaceholder.typicode.com/posts/1', { title: 'Updated Title' })
  .then((response) => {
    console.log('Post updated:', response.data);
  })
  .catch((error) => {
    console.error(error);
  });

PATCH Request:

axios.patch('https://jsonplaceholder.typicode.com/posts/1', { title: 'Updated Title' })
  .then((response) => {
    console.log('Post partially updated:', response.data);
  })
  .catch((error) => {
    console.error(error);
  });

These examples demonstrate how Axios makes it simple to send both PUT and PATCH requests to update resources either entirely or partially.

Executing DELETE Requests with Axios

For sending DELETE requests using Axios:

axios.delete('https://jsonplaceholder.typicode.com/posts/1')
  .then(() => {
    console.log('Post deleted successfully');
  })
  .catch((error) => {
    console.error(error);
  });

Axios provides an intuitive and consistent API for handling various HTTP request methods. It automatically serializes and deserializes JSON data, streamlining the process of sending and receiving data.

Fetch API: The Native Alternative

The Fetch API is a native JavaScript API designed for HTTP requests. It is readily available in modern browsers, making it a valuable tool for React developers. However, it may require a more manual approach compared to Axios.

Initiating a GET Request with Fetch

To perform a GET request using the Fetch API within a React component:

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

function App() {
  const [data, setData] = useState([]);

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

  return (
    <div>
      {/* Display data here */}
    </div>
  );
}

export default App;

This example closely resembles the Axios approach but uses the native Fetch API instead.

Sending a POST Request with Fetch

Making a POST request with the Fetch API requires a bit more manual configuration:

import React, { useState } from 'react';

function App() {
  const [postData, setPostData] = useState({ title: '', body: '' });

  const handleSubmit = () => {
    fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(postData),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log('Post created:', data);
      })
      .catch((error) => {
        console.error(error);
      });
  };

  return (
    <div>
      {/* Create a form for user input */}
      <form>
        <input
          type="text"
          placeholder="Title"
          onChange={(e) => setPostData({ ...postData, title: e.target.value })}
        />
        <textarea
          placeholder="Body"
          onChange={(e) => setPostData({ ...postData, body: e.target.value })}
        />
        <button type="button" onClick={handleSubmit}>
          Create Post
        </button>
      </form>
    </div>
  );
}

export default App;

In this example, we explicitly set the method, headers, and body of the request.

Handling PUT and PATCH Requests with Fetch

For PUT and PATCH requests with the Fetch API:

PUT Request:

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ title: 'Updated Title' }),
})
  .then((response) => response.json())
  .then((data) => {
    console.log('Post updated:', data);
  })
  .catch((error) => {
    console.error(error);
  });

PATCH Request:

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ title: 'Updated Title' }),
})
  .then((response) => response.json())
  .then((data) => {
    console.log('Post partially updated:', data);
  })
  .catch((error) => {
    console.error(error);
  });

These examples illustrate how the Fetch API allows you to perform PUT and PATCH requests, albeit with additional manual configuration.

Handling DELETE Requests with Fetch

To send a DELETE request with the Fetch API:

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'DELETE',
})
  .then(() => {
    console.log('Post deleted successfully');
  })
  .catch((error) => {
    console.error(error);
  });

The Fetch API offers flexibility but entails more manual effort when compared to Axios. Developers must explicitly set request headers and handle responses.

Making the Right Choice

In summary, both Axios and the Fetch API have their merits. Axios simplifies the process of making HTTP requests with a consistent API and automatic JSON serialization/deserialization. In contrast, the Fetch API is built into modern browsers and is a great choice if you prefer native solutions.

When deciding between the two, consider your project's requirements, your team's familiarity with each method, and your desire for browser compatibility. Regardless of your choice, both Axios and the Fetch API provide powerful tools for handling HTTP requests in your React applications.

In the end, the choice between Axios and the Fetch API will depend on your specific project needs and your personal or team preferences. Both offer effective ways to manage HTTP requests in React applications, and understanding their strengths and differences will enable you to make an informed decision for your development endeavors.

So, whether you opt for Axios's simplicity or the Fetch API's native capabilities, rest assured that you have the tools to handle HTTP requests effectively in your React projects.