Reputation: 1415
I'm building a shopping cart in a react/redux application and cannot delete the item from my array.
Here's the code I have right now.
case REMOVE_ITEM:
const cloned_array = state.items.slice()
cloned_array.splice(action.payload, 1)
return { ...state, items: cloned_array }
I am trying to clone the items array inside my state. Then splice that array with the index being sent to the reducer in my action.payload. Then return state with the items array being set to the clonedArray.
This results with the first item in my items array being delete instead of the item that is sitting in the index sent to the reducer.
Upvotes: 1
Views: 51
Reputation: 15688
You can do that in one method using .filter()
. It achieves the same goal that .slice
wants but now you don't need to save the sliced output in a separate array.
case REMOVE_ITEM:
return {
...state,
items: state.items.filter((item, index, array) => {
return index !== action.payload
})
}
Upvotes: 1