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?
>Solution :
- Add a default value as empty array to
useStateto make sure thatmap()always exist. (The first render willmapon an empty array, which is fine since there is not data yet)const [users, setUsers] = useState([]); useEffectcallback should not be await/async, removed that- You didn’t
returnanything from yourmap(), I’ve changed it to:{ users.map((user) => { return <div>{user.name}</div> }) }Or as the short-hand return style:
{ users.map(user => <div>{user.name}</div>) }
const { useState, useEffect } = React;
const App = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users/')
.then(response => response.json())
.then(data => setUsers(data))
}, []);
return (
<div>
{
users.map((user) => {
return <div>{user.name}</div>
})
}
</div>
)
}
ReactDOM.render(<App />, document.getElementById("react"));
html, body { height: 100vh; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>