Search code examples
javascriptreactjsreact-nativereact-reduxcart

Prevent redux from adding duplicate items to cart


I am using redux to put products in a cart for a react native project. At the moment it's functional, but I can add duplicate items. I want to prevent that.

What's the best way to modify the reducer that will stop storing duplicates?

My Reducer:

const cartItems = (state = [], action) => {
  //action type are the constatns
  switch (action.type) {
    case ADD_TO_CART:
      // TODO: dont add duplicates
      return [...state, action.payload];
      
    case REMOVE_TO_CART:
      //filter through the single item that matches payload and remove it
      return state.filter(cartItem => cartItem !== action.payload);
    case CLEAR_TO_CART:
      //return empty state which clears cart
      return (state = []);
  }
  //return the state
  return state;
};

My action:

export const addToCart = (payload) => {
    return {
        type: ADD_TO_CART,
        payload,
    }
}

Solution

  • Use find to check to see if an object with that product ID exists in state. If it does return the state otherwise return the updated state.

    const { product_id } = action.payload;
    const dupe = state.find(obj => obj.product_id === product_id);
    return dupe ? state : [...state, action.payload ];