React Context API App 구현 (3)

Suyeon Lee·2023년 9월 24일
0
post-thumbnail

데이터를 업데이트 해 주는 함수

const newOrderCounts = {...orderCounts};

스프레드 오파라이터를 사용해서 기존의 orderCounts를 복사해 준다


const orderCountsMap = orderCounts(orderType);
orderCountsMap.set(itemName, parseInt(newItemCounts));
  • orderCounts의 orderType -> products 또는 options
  • .set: orderCounts에 아이템을 추가
  • parseInt: string 형식을 int 형식으로 변경

return [{ ...orderCounts }, updateItemCount];
  • 업데이트 할 데이터 & 업데이트 함수

상품 Count를 이용한 가격 계산


const [totals, setTotals] = useState({
	products: 0,
	options: 0,
	total: 0
  });
  • 총 개수를 초기화 해 준 State 생성

const productsTotal = caculateSubtotal("products", orderCounts);
const optionsTotal = caculateSubtotal("options", orderCounts);\
const total = productsTotal +  optionsTotal;
  • 총 개수를 초기화 해 준 State 생성

  • optionCount 0으로 초기화, count를 받아올 때마다 optionCount += count
  • return 되는 값 -> optionCount * 타입에 따른 pricePerItem

orderContext 사용하기


orderContext.js

export const OrderContext = createContext();

Type.js

useContext를 이용해서 OrderContext 불러 오기


updateItemCount는 함수기 때문에 함수 표기


계산된 가격 보여 주기

여행 가격은 각 상품의 숫자를 올리거나 내릴 때 (Produtcs 컴포넌트),
옵션은 각 옵션의 체크 박스를 체크하거나 제거할 때 (Options 컴포넌트)
-> 해당 두 컴포넌트에 updateItemCount Prop 전달

Type.js

orderContext로 가져온 함수를 ItemComponent에 전달


Products.js

input 내 onChange에 handleChange 이벤트 추가 => 현재 개수를 e.target.value로 받아오고 props로 넘긴 함수에 전달


Options.js

input 내 onChange에 updateItemCount 사용
=> e.target.checked로 True & False 설정

profile
매일 렌더링하는 FE 개발자

0개의 댓글