0

I have a delete button on a todo list, and the splice isn't working properly. I get the id of the button and simply want to delete that item.

<ul>
                          {this.state.tasks.map((task, i) =>
                                <li key={i}>
                                    {task}
                                    <button id={i} onClick={this.removeTask}>Delete</button>
                                </li>
                            )}
</ul>

removeTask = (event) => {
                    // console.log(event.target.id);
                    const index = parseInt(event.target.id);
                    console.log(index);

                    this.setState(state => ({
                        tasks: [...state.tasks].splice(index,1),
                        count: state.count - 1,
                    }))
                }
  • 1
    Splice should be on a standalone line beforehand - it mutates the existing array and returns the removed elements, but you don't care about the removed elements. (Or, even better, don't use `splice` - `filter` would be better) – CertainPerformance Jun 03 '22 at 22:48
  • ahh I see, so tasks was being assigned what splice was returning, and not the modified array without the element that just got deleted – Francisco Gutierrez Ramirez Jun 03 '22 at 22:50

0 Answers0