javascriptreactjsarraysuse-reducer

How to remove an element from array, that array is a state of useReducer


I have a cart array of carted products. Now i want remove a product using useReducer. I can add products to the cart. But I am not getting the how will i remove that product from the cart. The cart array is a array of object evey obecjt is a product that has name, price, id etc. What will be the logic in this action?

enter image description here


export const initialState = {
  loading: false,
  products: [],
  error: false,
  cart: [],
  wishlist: [],
};

export const productReducer = (state, action) => {
  switch (action.type) {
    case actionTypes.FETCHING_START:
      return {
        ...state,
        loading: true,
        error: false,
      };
    case actionTypes.FETCHING_SUCCESS:
      return {
        ...state,
        loading: false,
        products: action.payload,
        error: false,
      };
    case actionTypes.FETCHING_ERROR:
      return {
        ...state,
        loading: false,
        error: true,
      };
    case actionTypes.ADD_TO_CART:
      return {
        ...state,
        cart: [...state.cart, action.payload],
      };
    case actionTypes.ADD_TO_WISHLIST:
      return {
        ...state,
        wishlist: [...state.wishlist, action.payload],
      };
    case actionTypes.REMOVE_FROM_CART:
      return {
        ...state,
        cart: [...state.cart, action.payload],
      };
    default:
      return state;
  }
};

Solution

  • You've said the cart items have an id. I'm going to assume those are unique.

    That being the case, your action should have the id of the cart item to remove ({ type: actionTypes.REMOVE_FROM_CART, id: ___ }), then the update creates a new array via filter that only keeps the cart items that don't match the action's id:

    case actionTypes.REMOVE_FROM_CART:
        return {
            ...state,
            cart: state.cart.filter(({id}) => id !== action.id),
        };
    

    Or if the action can contain the actual cart item, just compare directly:

    case actionTypes.REMOVE_FROM_CART:
        return {
            ...state,
            cart: state.cart.filter((item) => item !== action.item),
        };