How to delete an item from an array of objects in React

I want to remove a task from your Todolist. I implement a handle function that removes the desired task from the tasks array when a delete button is clicked using the filter function. Then update the state. But if the button is clicked, the desired task does not get removed or deleted.
below is my code

import React from "react";
import { useState } from "react";
import '../App.css'
let nextId = 0;

 function Todolist (){

    const [tasks, setTasks] = useState([]);
    const [input, setInput] = useState('')
    
    const handleChange = (e)=>{
        setInput(e.target.value);

    }

     const addTask = () =>{
        if(input.trim()){
            setTasks([...tasks, {text:input, completed: false, id: nextId++}]);
            setInput('');
        }

     }

     
     const deleteTask = item =>{
        const newTasks = tasks.filter(task => task.id !== item.id);
        setTasks(newTasks);
    }

    return ( 
        
        <div className="todolist-container">
            <h3>Big Todos</h3>
            <ul>
                {tasks.map((task, index) => (
                    <li key={index} className={task.completed? 'task completed': 'task'}>
                        <span>{task.text}</span>
                        <button onClick={deleteTask}>delete</button>

                    </li>
                ))}     
            </ul>
            <input className="todo" type="text" value={input} onChange={handleChange}/>
            <button onClick={addTask}>add</button>
        </div>

    )
}

export default Todolist;

Your deleteTask function expects an argument to be passed to it (the argument will be assigned to the item parameter). Based on the body of your deleteTask function, it is expected that this argument will have an id property i.e. you expect to be able to access item.id.

// You wrote:
<button onClick={deleteTask}>delete</button>

Since you aren’t explicitly passing an argument to the deleteTask function, so the event object will be passed as the argument. But, the event object doesn’t have an id property, so none of the tasks will fail the condition    task => task.id !== item.id    and all tasks will be retained.

// Try changing to:
<button onClick={()=>deleteTask(task)}>delete</button>

When the button is clicked, it will pass the appropriate task (being provided by your map statement) as the argument to the deleteTask function.

3 Likes

Your solution works. But I dont understand how or why? please explain further and in details

The above explanation is already as detailed and clear as it can possibly be. I’d recommend you take your time to get a grasp and and ask a more specific and in depth question in case you don’t understand certain aspects of it before you ask more of other user’s time because it is not clear where the confusion comes from.