Data Fetching from API in React
Data fetching is a common task in React applications, and there are several approaches and libraries you can use to fetch data from an API.
Using the fetch API method
The fetch API is built into modern browsers and allows you to make HTTP requests very easily. It returns a Promise that resolves to the response from the server.
To make a simple GET request with fetch we just need to include the URL endpoint to which we want to make our request. We will make this request once our React component has mounted.
Let’s see the example:
import React, { useState, useEffect } from "react"; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { fetch("https://api.example.com/data") .then((response) => response.json()) .then((data) => setData(data)) .catch((error) => console.error("Error fetching data:", error)); }, []); return ( <div> <ul> {data.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); } export default MyComponent;
Here the useEffect hook is used to perform data fetching when the component mounts. It runs the provided function as a side effect. In this case, it fetches data from the URL “https://api.example.com/data”. When the response is received, it’s converted to JSON
and the setData function is called to update the `data` state. The empty dependency array
[] ensures that this effect runs only once when component mounts.
Using Axios
Axios is a popular third-party library for making HTTP requests. It provides a simpler and more convenient way to handle network requests compared to the fetch API.
So first install Axios using npm. By running this command in terminal:
npm install axios
Then you can use Axios to fetch data from an API like this:
import React, { useState, useEffect } from "react"; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { axios.get('https://api.example.com/data') .then(response => setData(response.data)) .catch(error => console.error('Error fetching data:', error)); }, []); return ( <div> <ul> {data.map((item) => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); } export default MyComponent;