skip to Main Content

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?

2

Answers


  1. Hello I’m just making a guess as there is not enough code to pinpoint exactly the issue. The splice function modifies the state.books array, so that might be why it is working.

    For the array filtering function, you would need to assign the results to state.books.

    Login or Signup to reply.
  2. 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>
    )}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search