Can someone please explain me this code from ReactJS?

Viewed 53

can anyone please explain me this code? I am not able to understand as in what's happening here.

const cartReducer = (state, action) => {
  if (action.type === "ADD") {
    const updatedTotalAmount =
      state.totalAmount + action.item.price * action.item.amount;

    const existingCartItemIndex = state.items.findIndex(
      (item) => item.id === action.item.id
    );

    const existingCartItem = state.items[existingCartItemIndex];
    let updatedItems;

    if (existingCartItem) {
      const updatedItem = {
        ...existingCartItem,
        amount: existingCartItem.amount + action.item.amount,
      };
      updatedItems = [...state.items];
      updatedItems[existingCartItemIndex] = updatedItem;
    } else {
      updatedItems = state.items.concat(action.item);
    }

    return {
      items: updatedItems,
      totalAmount: updatedTotalAmount,
    };
  }
  return defaultCartState;
};
3 Answers

Reducers were popularized by Redux but are not a concept inherent to Redux in the sense that you can write a reducer without any import from Redux. A reducer is a concept for a particular kind of function i.e.:

a function that receives the current state and an action object, decides how to update the state if necessary, and returns the new state: (state, action) => newState. "Reducer" functions get their name because they're similar to the kind of callback function you pass to the Array.reduce() method.

Source: Redux docs

React now comes with a useReducer hook built-in. See Hooks API Reference.

I have added some comments to your code I hope this makes the code a bit more understandable.

const cartReducer = (state, action) => {
  // Adding an Item to Cart
  if (action.type === "ADD") {
    // Calculated Cart Total: existing Total + (new Item Price * new item Quantity)
    const updatedTotalAmount = state.totalAmount + action.item.price * action.item.amount;

    /* 
     * Finding Items Index in the Cart Array using the Item ID.
     * Index will be Returned only if Item with same od already exist otherwise -1
     */
    const existingCartItemIndex = state.items.findIndex((item) => item.id === action.item.id);
    /*
     * Getting the CartItem Based on the Index.
     * If the value is -1 i.e., item already doesn't exist, then this code will return undefined
     */
    const existingCartItem = state.items[existingCartItemIndex];

    let updatedItems;
    // existingCartItem will have an Object(which evaluates to true) only if Item already existed in Cart
    if (existingCartItem) {
      // Creating updatedItem by spreading the existingItems data + updating amount/Quantity to: existing Quantity + new Quantity
      const updatedItem = {
        ...existingCartItem,
        amount: existingCartItem.amount + action.item.amount,
      };

      // Making a Copy of Items Array & Replacing Existing Item with new/updated entry
      updatedItems = [...state.items];
      updatedItems[existingCartItemIndex] = updatedItem;
    } else {
      // If the Item doesn't already exist in Cart then we Just add that New Item to the Cart
      updatedItems = state.items.concat(action.item);
    }

    // Return the State with Updated Items List & total Amount
    return {
      items: updatedItems,
      totalAmount: updatedTotalAmount,
    };
  }

  // Default State Return
  return defaultCartState;
};

Related