Fetch Data in React JS in modern way

There are several ways to fetch data in a React application. Here are some of the most common:

Fetch API :

The Fetch API is a built-in browser API for fetching resources, including data from a server. It returns a Promise that resolves to the response object. You can use the Fetch API in combination with React’s useEffect hook to fetch data and update the component state.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      <h1>Data:</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

Axios:

Axios is a popular library for making HTTP requests from a browser or node.js. It returns a Promise that resolves to the response object. You can use Axios in combination with React’s useEffect hook to fetch data and update the component state.

Website

Tags: Data Fetch JS