Reputation: 39
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
Reputation: 19070
You should filter out the product if it is in the Store and add the new action.payload
quantity
, price
, total
, quantity
is updatedCode:
case ADD_TO_CART:
return [...state.filter(p => p.id !== action.payload.id), action.payload];
Upvotes: 1
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
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
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