DeepakD
Reactiflux4y ago
4 replies
Deepak

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;
    },

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 ?
Was this page helpful?