Using Fetch API and Axios for HTTP Requests in React JS

In this article, we will learn how to use both the Fetch API and Axios to make HTTP requests in a React JS application. These tools allow us to retrieve and send data from a backend or external API.

Fetch API Example

The Fetch API is a built-in JavaScript API for making HTTP requests. Below is an example of using it in a React component:

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

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

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

      return (
          

Fetch API Example

{data ? (

Title: {data.title}

Body: {data.body}

) : (

Loading...

)}
); } export default FetchExample;

In this example, we fetch a post from a sample API and display the title and body. The useEffect hook ensures the fetch runs after the component mounts.

Axios Example

Axios is a popular JavaScript library for HTTP requests. It is simpler to use compared to Fetch API and provides additional features such as request cancellation and interceptors. Here is an example:

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

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

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

      return (
          

Axios Example

{data ? (

Title: {data.title}

Body: {data.body}

) : (

Loading...

)}
); } export default AxiosExample;

In this example, Axios is used to fetch the same data. The syntax is more concise, and Axios automatically parses JSON responses.

Key Differences

  • Fetch API is built-in and does not require additional installation.
  • Axios provides a cleaner syntax and more features like request/response interceptors, automatic JSON parsing, and timeout handling.

Both Fetch API and Axios are excellent tools for making HTTP requests in React. Choose the one that best fits your project requirements.





Advertisement