R
Reactiflux

Deepak – 05-50 Aug 31

Deepak – 05-50 Aug 31

DDeepak8/31/2022
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 ?
UUUnknown User8/31/2022
Message Not Public
Sign In & Join Server To View
DDeepak8/31/2022
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.
UUUnknown User8/31/2022
Message Not Public
Sign In & Join Server To View
DDeepak8/31/2022
Yeah , i got it
UUUnknown User8/31/2022
Message Not Public
Sign In & Join Server To View

Looking for more? Join the community!

R
Reactiflux

Deepak – 05-50 Aug 31

Join Server