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
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
.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.If you want to use the index and filter:
If you would like to use the book title to remove a book from state then pass the book’s title value.