As I wrote above, I can’t print the data recovered from the fetch, I’ve been on this for some time without any results.
I’m new to React and learning how to use hooks.
The error I’m getting is:
Cannot read properties of undefined (reading ‘map’)
import React, { useEffect, useState } from 'react';
import './App.css';
export default function App() {
const [users, setUsers] = useState();
useEffect(async () => {
await fetch('https://jsonplaceholder.typicode.com/users/').then(response => response.json()).then(data => setUsers(data))
}, []);
return (
<div>
{
users.map((user) => {
<div>{user.name}</div>
})
}
</div>
)
}
Can you kindly help me?
2
Answers
useState
to make sure thatmap()
always exist. (The first render willmap
on an empty array, which is fine since there is not data yet)useEffect
callback should not be await/async, removed thatreturn
anything from yourmap()
, I’ve changed it to:Or as the short-hand return style:
The issue is that
users
isundefined
at the start, you have 2 ways to solve this:users
:useState([])
users
is undefined