React: using the Fetch API

React: using the Fetch API

In this article, we will see how to use the Fetch API in React to get and manage data.

The Fetch API is a Javascript interface that allows you to make HTTP requests and handle responses asynchronously. This API is widely used in React to fetch data from REST APIs and update component state dynamically. In this article, we will see how to use the Fetch API in React to get and manage data.

We can use the fetch() function to make an HTTP request and fetch the data. For example, if we wanted to retrieve data from a REST API, we could use the following code:

 fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));

In this code, the fetch() function is used to make an HTTP request to https://api.example.com/data. Once the response is obtained, the json() method is used to convert the data into JSON format. Finally, the data is logged as an example to the console using the console.log() method.

Also, to get the most out of the Fetch API, we can use its configuration feature. For example, if we wanted to include authentication information in the HTTP request, we could use the following code:

 fetch('https://api.example.com/data', {
        method: 'GET',
        headers: {
        'Authorization': 'Bearer ' + token
        }
})
.then(response => response.json())
.then(data => console.log(data));

In this code, we are passing a configuration object as the second parameter of the fetch() function. The configuration object includes information such as the HTTP method used (in this case GET) and HTTP request headers, including authentication with the Bearer token.

Finally, we can robustly handle errors by using the catch() method to catch any errors in the HTTP request or data handling. For example, we could use the following code:

 fetch('https://api.example.com/data')
    .then(response => {
        if (!response.ok) {
            throw new Error(response.status);
        }
        return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));

In this code, we are using the ok property to check if the HTTP response was successful. If the response is invalid, an exception is raised with throw. Otherwise, the data is converted to JSON format and logged to the console.

We can abstract the logic seen above into a function that takes advantage of the Fetch API.

export async function getRequest(url = '') {
        try {
            const response = await fetch(url);
            if(!response.ok) {
                throw new Error(response.status);
            }
            return await response.json();
        } catch(err) {
            return [];
        }
}

Then we can use this function in our components to change the value of a state property.

import { useState, useEffect } from 'react';
import { getRequest } from './lib/api';

export default function Test() {
    const [posts, setPosts] = useState([]);
    
    useEffect(() => {
            getRequest('https://api.example.com/posts').then(data => {
                setPosts(data);
            });
    }, []);
    
    return (
        <></>
    );
}

In short, the Fetch API is a powerful tool for making asynchronous HTTP requests in React.