Md. Kamrul Islam
Md. Kamrul Islam

Reputation: 39

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

Upvotes: 0

Views: 1126

Answers (4)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

You should filter out the product if it is in the Store and add the new action.payload

  • This will ensure that payload quantity, price, total, quantity is updated

Code:

case ADD_TO_CART:
  return [...state.filter(p => p.id !== action.payload.id), action.payload];
  

Upvotes: 1

Andy
Andy

Reputation: 63524

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

Upvotes: 2

tomnyson
tomnyson

Reputation: 297

you must check duplicate first before call action add_cart

case 1: if not has exists => push in array redux store

case 2: if has item => consider change property example increase number quantity product

Upvotes: 1

Abrah_dago_313
Abrah_dago_313

Reputation: 210

You can add some code before doing something like:

return {...state, cart: [...state.cart].push(payload)}

. for example:

const lookForCart = state?.cart?.find(crt => crt?.cardId === payload?.cardId)
if (lookForCart) return state
return {...state, cart: [...state.cart].push(payload)}

Upvotes: 1

Related Questions