I'm new to react and don't understand 1 thing with useState hook:
import {useEffect, useState} from "react";
export default function People() {
const [people, setPeople] = useState(null)
useEffect(() => {
const fetchData = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users")
const data = await response.json()
setPeople(data)
}
fetchData()
}, [])
return (
<>
<h1>People:</h1>
<ul>
{people && people.map(({id, name, email, username, phone, website}) => {
return (<div key={id}>
<li><h2>{name}</h2><p>{email}</p></li>
<p>{username}</p>
<p>{phone}</p>
<p>{website}</p>
</div>)
})}
</ul>
</>)
}
Why when I delete "people &&" I get error: "Cannot read properties of null (reading 'map')". But when I check for the existence of "people" the code works.
Why is this happening? Is this a feature of the hook? Thank you!
CodePudding user response:
I'm pretty new to react myself. In my short experience, I've would say setting your initial state of people to an empty array would solve this for you.
Because getting the data is happening asynchronously. The render is first trying to map people with the value of null which throws an error before it can try again
Hope this helps :)
CodePudding user response:
Your initial people
state value is null.
As react component behave as asynchronous, the .map()
method executed over null.
You can solve this issue by doing two method.
Method-1:
people &&
Method-2: Assigning initial value as empty array for people state.
const [people, setPeople] = useState([])
CodePudding user response:
Pass [] in the useState insted of null. Because we can not iterate loop over null datas. Your code should be look like below:
const [people, setPeople] = useState([])