Home > Enterprise >  Delete Item from Array and Update (React)
Delete Item from Array and Update (React)

Time:09-05

I'm Trying to Delete an Item from a Array but it is not updating

const todoList = ["wake up", "brush", "code", "eat"];
const [todo, setTodo] = useState(todoList);

const handleDelete = (idx) => {
 todoList.splice(idx, 1); // ["wake up", "code", "eat"]
 setTodo(todoList); // Does not Change `todo`
}

<ul>
{todo.map((todo, index) => (<li key={index}>{todo}<span className="materialsymbols-outlined" onClick={() => handleDelete(index)}>delete</span></li>))}
</ul>

im Struggling on this for 3 hrs, Thanks in Advance!

CodePudding user response:

You need to change your handleDelete method so that it filters a removed index and creates a new array with a new reference, for example:

  const handleDelete = (idx) => {
    const filteredTodos = todo.filter((_, index) => index !== idx);
    setTodo(filteredTodos);
  };

CodePudding user response:

You need to update the todoList reference to update the state as splice delete an element from the array but keep the reference, Also I suggest using setState callback.

const handleDelete = (idx) => {
 setTodo(prev => {
  prev.splice(idx, 1)
  return [...prev]
 });
}

CodePudding user response:

You could maybe do something like this:

const todoList = ["wake up", "brush", "code", "eat"];
const [todo, setTodo] = useState(todoList);

const handleDelete = (idx) => {
 let arr = [...todoList];
 arr.splice(idx, 1);
 setTodo(arr);
}

This should normally work. Hope it helps!!!

  • Related