-2

I have the following object

 this.state.books = {"test": "test1"}

I'm trying to delete a key from that object, but I'm not able to. Here's my code

 var books = Object.assign({}, this.state.books);
            delete books["test"];
            this.setState({
                books: books,
                loading: false
            });

setState is not triggering and rendering a new books object

Chris Hansen
  • 7,813
  • 15
  • 81
  • 165

1 Answers1

0

you can use destructuring to delete the key.

const { test: gone, ...newBooks } = this.state.books
console.log('gone', gone);
console.log('newBooks', newBooks);

this.setState( prev => ({ ...prev, books: newBooks }))

codesandbox

Someone Special
  • 12,479
  • 7
  • 45
  • 76