Deepak – 05-50 Aug 31

Hello everyone, i'm trying to understand the else part of the code.
reducers: {
addToCart: (state, { payload }) => {
const isItemExist = state.cartItems.find(
(item) => item.id === payload.id
);
if (!isItemExist) {
state.cartItems = [...state.cartItems, { ...payload, quantity: 1 }];
} else {
state.cartItems = state.cartItems.map((item) => {
if (item.id === payload.id) {
return { ...item, quantity: item.quantity + 1 };
} else {
return item;
}
});
}
state.quantity++;
state.totalAmount += payload.price;
},
reducers: {
addToCart: (state, { payload }) => {
const isItemExist = state.cartItems.find(
(item) => item.id === payload.id
);
if (!isItemExist) {
state.cartItems = [...state.cartItems, { ...payload, quantity: 1 }];
} else {
state.cartItems = state.cartItems.map((item) => {
if (item.id === payload.id) {
return { ...item, quantity: item.quantity + 1 };
} else {
return item;
}
});
}
state.quantity++;
state.totalAmount += payload.price;
},
In my understanding, If i was suppose to addToCart i would push the item to cartItem but here i am returning the item. can anyone explain me how does this work ?
UU
Unknown User596d ago
D
Deepak596d ago
Thanks, i think understood. I was confused that why aren't the pushing the item to cart but it is pushing on if statement where it checks if the item exist.
UU
Unknown User596d ago
D
Deepak596d ago
Yeah , i got it
UU
Unknown User595d ago