Fetch Data in React JS in modern way
<p>There are several ways to fetch data in a React application. Here are some of the most common:</p>
<h2>Fetch API :</h2>
<p>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.</p>
<pre>
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>
);
}</pre>
<h2>Axios:</h2>
<p>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.</p>
<p><a href="https://medium.com/@aizaz2117/fetch-data-in-react-js-in-modern-way-f9fe3c8c27f2">Website</a></p>