Hye, I'm new to react-redux I'm struggling to convert a nested if else statement into switch statement. Can anyone tell me how to do that? below is my code
if (action.type === ADD_TO_CART) {
let addedItem = state.jeans.find((item) => item.id === action.id);
let existed_item = state.addedItems.find((item) => action.id === item.id);
if (existed_item) {
addedItem.quantity += 1;
return {
...state.jeans,
total: state.total + addedItem.price,
};
} else {
addedItem.quantity = 1;
let newTotal = state.total + addedItem.price;
return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
}
}
I guess you just wanted to switch it from if else to switch right?
In this case you can the following I guess:
if (action.type === ADD_TO_CART) {
let addedItem = state.jeans.find((item) => item.id === action.id);
let existed_item = state.addedItems.find((item) => action.id === item.id);
switch(existed_item){
case !undefined: {
addedItem.quantity += 1;
return {
...state.jeans,
total: state.total + addedItem.price,
};
}
default: {
addedItem.quantity = 1;
let newTotal = state.total + addedItem.price;
return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
}
}
}
And your sir is right. It should be written with switch as there is a good chance the list of actions types will increase and you'll have multiple cases.
It should be something like this:
s
switch(action.type) {
case ADD_TO_CART:
let addedItem = state.jeans.find((item) => item.id === action.id);
let existed_item = state.addedItems.find((item) => action.id === item.id);
if (existed_item) {
addedItem.quantity += 1;
return {
...state.jeans,
total: state.total + addedItem.price,
};
} else {
addedItem.quantity = 1;
let newTotal = state.total + addedItem.price;
return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
}
default:
return state; // or something else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With