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')
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;
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)
try to wrap the fetch in an async function which you call at the end of useEffect.