Search code examples
javascriptreactjsreduxreact-reduxredux-toolkit

Deleting product from added bags isn't working in Redux-Toolkit


I'm using Redux-Toolkit and trying to delete a product from my cart (Bag) but it's not working when I'm trying to use

removeBook(state, action) {
  state.books = state.books.filter(book => book.title !== action.payload)
}

whereas it works in this way

removeBook(state, action) {
  state.books.splice(action.payload, 1)
}

What is any explanation for this?


Solution

  • If using the Array.prototype.splice method works then it would seem you are dispatching the removeBook and passing an index as the payload value.

    removeBook(state, action) {
      state.books.splice(action.payload, 1);
    }
    
    {books.map((book, index) => (
      <div key={book.title}>
        <h2>{book.title}</h2>
        <button
          type="button"
          onClick={() => dispatch(removeBook(index))} // <-- passing index
        >
          X
        </button>
      </div>
    )}
    

    If you want to use the index and filter:

    removeBook(state, action) {
      state.books = state.books.filter((book, index) => index !== action.payload);
    }
    
    {books.map((book, index) => (
      <div key={book.title}>
        <h2>{book.title}</h2>
        <button
          type="button"
          onClick={() => dispatch(removeBook(index))} // <-- passing index
        >
          X
        </button>
      </div>
    )}
    

    If you would like to use the book title to remove a book from state then pass the book's title value.

    removeBook(state, action) {
      state.books = state.books.filter(book => book.title !== action.payload);
    }
    
    {books.map((book) => (
      <div key={book.title}>
        <h2>{book.title}</h2>
        <button
          type="button"
          onClick={() => dispatch(removeBook(book.title))} // <-- passing title
        >
          X
        </button>
      </div>
    )}