DEV Community

Yash Smith
Yash Smith

Posted on

Page Not Rendering After Fetching Data from API

Hello,

I’m fetching data from an API and trying to display it on the frontend, but the page is not rendering properly. The console shows an error:

TypeError: Cannot read properties of undefined (reading 'map')
Enter fullscreen mode Exit fullscreen mode

Here’s my React component:

import { useEffect, useState } from "react";

const UsersList = () => {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetch("https://api.example.com/users")
            .then(res => res.json())
            .then(data => setUsers(data))
            .catch(error => console.error("Error fetching users:", error));
    }, []);

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

export default UsersList;
Enter fullscreen mode Exit fullscreen mode

Troubleshooting Attempts:
Checked API response, and it's returning data.
Console logs show users as undefined initially.
Tried adding users && users.map(...) but the issue persists.
Any ideas on how to resolve this? Thanks in advance!

Would you like more variations or different types of errors?

Top comments (1)

Collapse
 
ylmfuchs profile image
ylmFuchs

try to wrap the fetch in an async function which you call at the end of useEffect.

useEffect(() => {
  const fetchFunc = async () => {
     fetch("https://api.example.com/users")
              .then(res => res.json())
              .then(data => setUsers(data))
              .catch(error => console.error("Error fetching users:", error));
  })

  fetchFunc()
}, []); 
Enter fullscreen mode Exit fullscreen mode