Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native, How to convert nested if else into switch statement?

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,
      };
    }
  }
like image 316
Kanwarjeet Singh Avatar asked Nov 28 '25 11:11

Kanwarjeet Singh


2 Answers

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,
            };
        }
    }
}
like image 149
Berke Avatar answered Nov 30 '25 01:11

Berke


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
}
like image 38
D10S Avatar answered Nov 30 '25 01:11

D10S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!