Answer the question
In order to leave comments, you need to log in
Why does the Cannot read property 'map' of undefined error occur?
The code renders a list with a delete button, an input, and a button.
By clicking on the "X" button, the deleteLi function is called, which should delete the list item. But an error comes out:
TypeError: Cannot read property 'map' of undefined
import React, { useState } from 'react';
const Task = () => {
const [users, setUsers] = useState({user:['user1', 'user2', 'user3']});
const [li, setLi] = useState('');
const deleteLi = (index) => {
setUsers(users.user.filter((item,i) => i !== index));
};
const list = users.user.map((item, index)=>(
<li key={index}>
{item}
<button onClick = {()=>deleteLi(index)}> Х </button>
</li>
));
const handleChange = (e) => setLi(e.target.value);
const handleClick = () => setUsers({user:[...users.user, li]});
return <div>
<ul>{list}</ul>
<input type="text" onChange = {handleChange}/>
<input type="submit" onClick = {handleClick}/>
</div>
};
export default Task;
Answer the question
In order to leave comments, you need to log in
const [users, setUsers] = useState({user:['user1', 'user2', 'user3']});
setUsers(users.user.filter((item,i) => i !== index));
const list = users.user.map(...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question