How To Use Fetch Method In React?

Spread the love

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 on server requests. We might be having a server and database where the data is stored.

We make a call to the server using an api url for data. So whenever the server gets a request from api, it returns the data to the client.

We can handle this whole process by using the fetch method in React.

How to use the fetch method in React?

I will be explaining this example with react hooks as state management. We will be using a sample api server(https://api.sampleapis.com/codingresources/codingResources) to make api requests for 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);
                }
            )

    }
    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;

In the above code, we have used fetch method to get the data from the end point https://api.sampleapis.com/codingresources/codingResources  and displaying it on browser. If we notice, the fetch method, we have used two then() methods if the request get resolved. Basically, fetch is built on top of promise and in the 2nd then() method, we are getting the data from the promise. If we are using axios or any other plugins which are used for asynchronous calls, the promises are handled are handled by the plugin itself and we will be having only one resolve method which is then() to get the data. So, this is how we can use fetch() method to get the data asynchronously using React.

Leave a Comment