HDallakyan
HDallakyan

Reputation: 748

Redux - remove item from array

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;
};

Upvotes: 1

Views: 6236

Answers (2)

vitomadio
vitomadio

Reputation: 1140

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.

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281686

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.

Upvotes: 9

Related Questions