-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
  • 6,293
  • 12
  • 67
  • 141

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
  • 9,948
  • 5
  • 33
  • 65