I am using react context to add item to the cart and I want to prevent duplicate items being added in the cart, I have tried tweaking the code, but it seems like something is missed. Below is the code sample:
const cartReducer = (cartState, action) => {
switch (action.type) {
case "add-cart": {
const item = action.payload;
const existItem = cartState.cart.find((x) => x.id === item.id);
if (existItem) {
return {
cart: [...cartState.cart, action.payload],
};
} else
return {
...cartState,
cart: [...cartState.cart, action.payload],
};
}
}
};
export const CartProvider = (props) => {
const [cartState, dispatch] = useReducer(cartReducer, {
cart: [],
});
function addToCart(val) {
dispatch({
type: "add-cart",
payload: val,
});
}
CodePudding user response:
Why are you insert your item even if item already exists in the cart ?
You don't have to put your action.payload
in the cart if already exists
if (existItem) {
return { ...cartState };
} else {
return {
...cartState,
cart: [...cartState.cart, action.payload],
};
}