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;
};
HDallakyan
  • 740
  • 2
  • 9
  • 24
  • Possible duplicate of [Is this the correct way to delete an item using redux?](https://stackoverflow.com/questions/34582678/is-this-the-correct-way-to-delete-an-item-using-redux) – n1stre Sep 11 '18 at 06:36

2 Answers2

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.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • my action like this export const removeFromCard = (productsInCard) => { let nextTodoId = 0 return { type: ACTION_REMOVE_FROM_CARD, payload: productsInCard, index: nextTodoId++ } } – HDallakyan Sep 11 '18 at 06:53
  • but the first solution just remove first item from the array – HDallakyan Sep 11 '18 at 06:54
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.

vitomadio
  • 1,140
  • 8
  • 14