1

I have a reduce, so the ACTION_ADD_PRODUCTS call product list, the ACTION_ADD_TO_CARD action call adding products in the card and ACTION_REMOVE_FROM_CARD should remove from the card, but I can't understand how to make ACTION_REMOVE_FROM_CARD return, that when I click on one of the remove buttons, the item should be removed from the card array;

const initialState = {
  products: [],
  card: []
}

export const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case ACTION_ADD_PRODUCTS:
      return {...state, 
        products: action.payload}
    case ACTION_ADD_TO_CARD:
      return {
        ...state,
        card: [...state.card,  action.payload]
      }
    case ACTION_REMOVE_FROM_CARD:         
      return {
        card: [...state.card,  action.payload]
      }
    default:
  }
  return state;
};
1

2 Answers 2

9

While removing the item, you need to pass additional information with to the reducer, be it index or the id of the item.

If its index, you can simply use slice

case ACTION_REMOVE_FROM_CARD:  
      const index = action.payload.index      
      return {
        ...state,
        card: [...state.card.slice(0, index), ...state.card.slice(index + 1)]
      }

else if you pass the id, you can make use of filter

case ACTION_REMOVE_FROM_CARD:  
      const id = action.payload.id      
      return {
          ...state,
          card: state.card.filter((card) => card.id !== id)
      }

P.S. Also do not forget to return the other state parameters, not just card within the object.

Sign up to request clarification or add additional context in comments.

2 Comments

my action like this export const removeFromCard = (productsInCard) => { let nextTodoId = 0 return { type: ACTION_REMOVE_FROM_CARD, payload: productsInCard, index: nextTodoId++ } }
but the first solution just remove first item from the array
1

When it comes to remove items from array in reducer, I usually pass an index as actiin.payload, then just use array.splice(index, 1) to remove the item. In your case:

case ACTION_REMOVE_FROM_CARD: 
    let newCard = Object.assign([], this.state.card)
    newCard.splice(action.payload, 1) 
    return { card: [...state.card, newCard] }

Remember action.payload will be your desire index number you pass from the component action. Hope it could helps.

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.