0

i'm trying to use setState to update one property of a sub object of the state. What is the correct way to do this? I want to access the state and define which part I want to update, as opposed to update the entire state with a new state. Hope that makes sense...

class BooksApp extends React.Component {
  state = {
    books: []
  }

componentDidMount() {
  BooksAPI.getAll().then((books) => {
    this.setState({books})
  })
}
selectStateUpdate = (book,shelf) => {
  this.updateShelf(book, shelf);

}
updateShelf = (book, shelf) => {
  BooksAPI.update(book, shelf)
  .then(() => {
    for (var i=0; this.state.length < i; i++) {
      if (this.state.title === book.title) {
        this.setState({
          books[i].shelf: book.shelf
        })
      }
    }
  })
}
Robinj
  • 31
  • 1
  • 5
  • 1
    Possible duplicate of [Updating an object with setState in React](https://stackoverflow.com/questions/43638938/updating-an-object-with-setstate-in-react) – Roy J Apr 26 '18 at 18:16
  • I think you are asking how to just update particular entry in the `books` array instead of the whole `books` when only part of it change. Unfortunately it is not doable. @Ivan Burnaev answer is the way to do it, which will only trigger 1 event to let the component know that `state` has been change. – DJ. Apr 26 '18 at 18:41

1 Answers1

1

Try to change your state changing part to:

this.setState({
  books: this.state.books.map((item, index) => 
    index === i ? {...item, shelf: book.shelf} : item
  )
})
Ivan Burnaev
  • 2,690
  • 18
  • 27