How To Use Fetch Method In React?
In this article, you are going to learn how to use the fetch method in React.
The purpose of using the fetch method in an application is to get the data asynchronously from server requests. Usually, we have a server and database where the data is stored and we make a call to the server using an API URL. Whenever the server gets a request from the API, it returns the data to the client.
We can handle this whole process by using the native fetch method in React.
I will be explaining this example with React hooks for state management. We will be using a sample API server (https://api.sampleapis.com/csscolornames/colors) to make API requests for color data. So let’s begin.
Source Code
import React, { useState } from 'react';
const FetchExample = () => {
const [data, setData] = useState([]);
const [error, setError] = useState(null);
const getData = () => {
fetch("https://api.sampleapis.com/csscolornames/colors")
.then((response) => response.json())
.then(
(result) => {
setData(result);
},
(error) => {
setError(error.message || "An error occurred");
}
)
}
console.log(data);
return (
<div style={{ margin: 20 }}>
<button onClick={getData}>Click To Get Data From Api</button>
{
error ? (<div>Error: {error}</div>) : (data.map((item, i) => {
return <div key={i} style={{ color: item.hex }}>{item.name}</div>
}))
}
</div>
)
}
export default FetchExample;
How It Works
In the above code, we have used the fetch method to get data from the end point https://api.sampleapis.com/csscolornames/colors and display it in the browser.
If we examine the fetch method, we have chained two .then() methods. This is because fetch is built on top of Javascript Promises:
- The first
.then()receives the raw HTTP response and converts it into JSON viaresponse.json(), which itself returns a Promise. - The second
.then()receives the actual parsed data from the resolved JSON promise and we set it to ourdatastate.
If we were using libraries like Axios for asynchronous calls, the first promise conversion step is handled automatically, meaning we would only need one .then() block to get the data.
So, this is how we can use the fetch() method to fetch data asynchronously using React.
Happy Coding!