1

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.

1 Answer 1

1

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
    })
   }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.