Using fetch() in React JS with Example

1. Declare React state to store API data

First, we need to declare React State to store the list of users returned from the response of the API call.

Filtering Array of objects in React...
Filtering Array of objects in React JS
// Store list of all users
const [users, setUsers] = useState();

2. JS function to fetch API data and store the response

We need to declare a JS function to retrieve the data from an external URL in the following steps:

  1. We fetch the data from the “https://jsonplaceholder.typicode.com/todos/” URL using JavaScript fetch() API.
  2. Add a callback function to then() for converting the response into JSON format.
  3. The user React state is updated with the list of users from the API response.
// Function to collect data
const getApiData = async () => {
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/todos/"
  ).then((response) => response.json());

  // update the state
  setUsers(response);
};

3. Add useEffect to fetch API on page load

Once we have defined the function to retrieve the API data, it needs to trigger on page load. The getApiData() added into React useEffect() with empty dependency array, which ensures code is triggered once on page load.

useEffect(() => {
  getApiData();
}, []);

4. Generate JSX Code with React state

Finally, we need to display the details of every user. Hence we will generate JSX code for every user by using Array.map() and the callback function returns <div></div> with the user.id and user.title.

<div className="app">
  {users &&
    users.map((user) => (
      <div className="item-container">
        Id:{user.id} <div className="title">Title:{user.title}</div>
      </div>
   ))}
</div>

Final Solution Code

fetchapi-output
The output of fetch() API data

App.js

import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [users, setUsers] = useState();

  // Function to collect data
  const getApiData = async () => {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/todos/"
    ).then((response) => response.json());

    setUsers(response);
  };

  useEffect(() => {
    getApiData();
  }, []);

  return (
    <div className="app">
      {users &&
        users.map((user) => (
          <div className="item-container">
            Id:{user.id} <div className="title">Title:{user.title}</div>
          </div>
        ))}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);