Deepak
Deepak3y ago

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 ?
5 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Deepak
DeepakOP3y 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.
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Deepak
DeepakOP3y ago
Yeah , i got it
reactibot
reactibot3y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1014411888735555654