Thursday, 5 December 2024

Using Async and Await with the useEffect Hook in React to Fetch Data

This is continuation to my previous post, where I explained how to render the user details using promises and useEffect hook.

useEffect(() => {
    // This effect will run when the component is first rendered

    // Fetching data from an API
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data))  // Update the state with the fetched data
      .catch(error => console.error('Error fetching users:', error));

}, []);  // The empty dependency array means this runs only on the first render (once)

Above snippet can be written like below.

useEffect(() => {
    // This effect will run when the component is first rendered

    async function fetchUsers() {
      try {
        let response = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        let data = await response.json();
        setUsers(data);
      } catch (error) {
        console.error("Failed to fetch users:", error);
      }
    }

    fetchUsers();
  }, []); // The empty dependency array means this run only on the first render (once)

This code uses the useEffect hook to fetch a list of users from an external API (jsonplaceholder.typicode.com/users) when the component is first rendered. The fetchUsers function makes the request asynchronously, processes the response into JSON format, and updates the component's state with the retrieved data using setUsers. If the fetch operation fails, the error is caught and logged to the console. The effect runs only once because of the empty dependency array.

 

 

Follow below step-by-step procedure to build the application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘async-await-with-use-effect’.

 

Project structure looks like below.

 


Step 2: Create components folder in src/ folder and define UserDetails component.

 

UsersInfo.jsx

import React, { useState, useEffect } from "react";

export default function UsersInfo() {
  const [users, setUsers] = useState([]); // State to hold the users

  useEffect(() => {
    // This effect will run when the component is first rendered

    async function fetchUsers() {
      try {
        let response = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        let data = await response.json();
        setUsers(data);
      } catch (error) {
        console.error("Failed to fetch users:", error);
      }
    }

    fetchUsers();
  }, []); // The empty dependency array means this runs only on the first render (once)

  return (
    <div>
      <h1>User List</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

Step 3: Update main.jsx like below.

 

main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import UsersInfo from './components/UsersInfo'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <UsersInfo />
  </StrictMode>,
)

Step 4: Build and run the application by executing below commands.

  cd async-await-with-use-effect
  npm install
  npm run dev

Open the url 'http://localhost:5173/' in browser, you will see below screen.


 


You can download this application from this link.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment