score:2

Accepted answer

Whats wrong is that you are directly mutating the state and it doesn't re-render so the change is not reflected in your DOM. use setState to update state

componentWillMount() {
    BooksAPI.getAll().then((books) => {
      const tempBooks = [];
      books.forEach((book) => {
        if (this.state.shelf === book.shelf){
          // console.log(book);
          tempBooks.push(book);
        }
      })
      this.setState(prevState => ({books: [...prevState.books, ...tempBooks]}))
    })
  }

score:0

This is the correct fix. I want to add the book into the previous array.

  componentWillMount() {
    BooksAPI.getAll().then((books) => {
      books.forEach((book) => {
        if (this.state.shelf === book.shelf) {
          this.setState(prevState => ({books: [...prevState.books, book]}))
        }
      })
    })
  }

score:1

render() {
    let books = this.state.books;
    return (<div className="bookshelf">
      <h2 className="bookshelf-title">{this.titles[this.props.shelf]}</h2>
      <div className="bookshelf-books">
        <ol className="books-grid">
          {books.map((book) => return(<Book/>))}
        </ol>
      </div>
    </div>)
  }

Related Query

More Query from same tag