온라인 강의/React 완벽 가이드 [Udemy]

156. 더 복잡한 리듀서 로직 작업하기

유호야 2023. 6. 22. 16:52
반응형

장바구니에서 같은 항목들을 하나로 합치고 수량을 올리는 과정을 작성함

findIndex() 메서드 사용

 

CartProvider.js

import CartContext from './cart-context';
import { useReducer } from 'react';

const defaultCartState = {
  items: [],
  totalAmount: 0
}
const cartReducer = (state, action) => {
  if (action.type === 'ADD') {
    const exisitingCartItemIndex = state.items.findIndex(item => item.id === action.item.id);
    const exisitingCartItem = state.items[exisitingCartItemIndex];
    let updatedItem;

    let updatedItems = state.items.concat(action.item);
    if (exisitingCartItem) {
      updatedItem = {
        ...exisitingCartItem,
        amount: exisitingCartItem.amount + action.item.amount
      };
      updatedItems = [...state.items];
      updatedItems[exisitingCartItemIndex] = updatedItem;
    } else {
      updatedItems = state.items.concat(action.item);
    }

    const updatedTotalAmount = state.totalAmount + action.item.price * action.item.amount;
    return {
      items: updatedItems,
      totalAmount: updatedTotalAmount
    }

  } else if (action.type === 'REMOVE') {

  }

  return defaultCartState;
}

const CartProvider = props => {
  const [cartState, dispatchCartAction] = useReducer(cartReducer, defaultCartState);

  const addItemToCartHandler = item => {
    dispatchCartAction({ type: 'ADD', item: item });
  };

  const removeItemFromCartHandler = id => {
    dispatchCartAction({ type: 'REMOVE', item: id });
  };

  const cartContext = {
    items: cartState.items,
    totalAmount: cartState.totalAmount,
    addItem: addItemToCartHandler,
    removeItem: removeItemFromCartHandler
  };

  return <CartContext.Provider value={cartContext}>
    {props.children}
  </CartContext.Provider>
}

export default CartProvider;
반응형