Am a mutating state directly here

Hi , I was hoping someone can help me, I am just trying to not mutate state directly by creating copies, can someone have a look at my methods and see if i have done this properly, thanks!!

class BooksApp extends React.Component {
  state = {
    currentlyReading: [],
    wantToRead: [],
    read: [],
    searchedBooks: [],
    showSearchPage: false,
  };

  clearSearch = () => {
    let emptyArray = [];
    this.setState({
      searchedBooks: emptyArray,
    });
  };
  searchForBooks = async (e) => {
    let emptyArray = [];
    if (e.target.value === '') {
      return this.setState({
        searchedBooks: emptyArray,
      });
    }
    if (results.error) {
      return this.setState({
        searchedBooks: emptyArray,
      });
    }
    let filteredResults = results.filter((book) => {
      return book.imageLinks;
    });
    const allMyBooks = [
      ...this.state.currentlyReading,
      ...this.state.read,
      ...this.state.wantToRead,
    ];
    let newArrayOfBooks = filteredResults.map((searchedBook) => {
      let shelf = 'none';
      allMyBooks.map((myBook) => {
        if (searchedBook.id === myBook.id) {
          return (shelf = myBook.shelf);
        } else {
          return (searchedBook.shelf = shelf);
        }
      });
      return (searchedBook.shelf = shelf);
    });
    newArrayOfBooks = results.filter((book) => {
      return book.imageLinks;
    });
    this.setState({
      searchedBooks: newArrayOfBooks,
    });
  };
  updateBookshelves = async () => {
    let booksList = await BooksAPI.getAll();
    const currentlyReading = booksList.filter(
      (book) => book.shelf === 'currentlyReading'
    );
    this.setState({
      currentlyReading,
    });
    const wantToRead = booksList.filter((book) => book.shelf === 'wantToRead');
    this.setState({
      wantToRead,
    });
    const read = booksList.filter((book) => book.shelf === 'read');
    this.setState({
      read,
    });
  };

As far as I can tell, you’re doing good. Whenever you set state like this:

this.setState({prop:'val'})

you’re on the safe side.

This is not (just an example):

this.setState({prop:!this.state.prop})

A few summarizing bullets - hopefully all are correct:

  • There is a way to update the state inside setState, but you’ll probably come to it later on.
  • Outside useState, you’re doing well. Filter returns a new array, right?
  • Don’t use push, for example, and you’re good.

Hi, thanks for the answer, sorry for the delay in replying.