3

So I created React Todo App with an Object as a Todo List. Removing an item by key works with delete, but brings me back boolean instead of Object with the rest of the items.

  deleteTodo = (id) => {
const { todos } = this.state;
this.setState({
  todos: delete todos[id],
});

I get this in console:

Warning: Failed prop type: Invalid prop `todos` of type `boolean` supplied to `TodoList`, expected an object.
jo_va
  • 13,504
  • 3
  • 23
  • 47
Rizraelle
  • 31
  • 1
  • 6

2 Answers2

8

You should use immutable operations when using Redux. You should not change your state directly.

For that, you can use destructuring to exclude your todo from the todos, if your todos are in an object:

const { todos } = this.state;
const { [id]: _, ...newTodos } = todos;
this.setState({
    todos: newTodos
});

If the todos are in a list and since you cannot destructure an item by index from an array, use the slice method, which doesn't modify the array, but returns a modified copy:

const { todos } = this.state;
this.setState({
    todos: [...todos.slice(0, id), ...todos.slice(id + 1)];
});
jo_va
  • 13,504
  • 3
  • 23
  • 47
0

You have to firstly copy your state to an array so you have a clone of it.

Then you remove the unwanted id from your new array.

var newTodoArray = this.state;

newTodoArray.remove(id);

    this.setState({
      todos: newTodoArray,
   });

Something like the above.

Paddymac
  • 377
  • 1
  • 3
  • 19