Z
Z
zerabora2020-12-11 11:59:43
React
zerabora, 2020-12-11 11:59:43

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;


What is the cause of the error and how can I fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-12-11
@zerabora

const [users, setUsers] = useState({user:['user1', 'user2', 'user3']});

Here users is an object whose only property is an array.
setUsers(users.user.filter((item,i) => i !== index));

And here is an array.
const list = users.user.map(...

You try to read the user property of this array, which does not exist, you get undefined, and then ... Well, you have already seen the error message.
You would decide what users should be.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question