Why does this code give me: TypeError: items.map is not a function
?
const [items, setItems] = useState([])
const url = 'https://rickandmortyapi.com/api/character/1'
useEffect(() => {
async function fetchEmployees() {
const response = await fetch(url)
const fetchedEmployees = await response.json(response)
setItems(fetchedEmployees)
}
fetchEmployees()
}, [])
return (
<div>
{items.map((element) => (
<li>{element.name}</li>
))}
</div>
)
}
You don't need to pass the response inside response.json()
.
useEffect(() => {
async function fetchEmployees() {
const response = await fetch(url)
const fetchedEmployees = await response.json()
setItems(fetchedEmployees)
}
fetchEmployees()
}, [])
Since your API doesn't return an array, you can't use map
on items
. The following should do
return (
<div>
<li>{items.name}</li>
</div>
)
If you're trying to fetch an array of objects, you should probably check another endpoint that returns an array of characters like this https://rickandmortyapi.com/api/character. You can then map through items.results
to output the name
inside your component's JSX.