[9주차/오스카] 워크북 제출합니다.#94
Open
OscarKang1 wants to merge 4 commits into
Hidden character warning
The head ref may contain hidden characters: "\uc624\uc2a4\uce74/9\uc8fc\ucc28-\uc81c\ucd9c"
Open
Conversation
kcleverp
reviewed
May 29, 2026
|
|
||
| clearCart: () => set({ cartItems: [], amount: 0, total: 0 }), | ||
|
|
||
| calculateTotals: () => |
There was a problem hiding this comment.
zustand의 사용법을 잘 알고 계시고 사용하신 것 같아 좋습니다.
하지만 기존의 calculateTotals를 외부에서 매번 수동으로 호출하게 유도하는 구조는 잠재적인 UI 동기화 버그가 있을 수 있습니다.
현재 increase, decrease, removeItem 액션들이 실행될 때, cartItems만 갱신할 뿐 amount와 total을 업데이트하지 않고 있습니다.
다른 컴포넌트에서 액션을 호출한 후 calculateTotals()를 호출해 주어야만 UI에 값이 동기화 될 것으로 보입니다.
Zustand에는 셀렉터 기능을 사용하여 상태가 변할 때 총액과 총 수량을 계산하게 하는 로직을 구축하면 다른 컴포넌트에서는 해당 훅 하나만 호출하면 스토어에 있던 구독하는 상태가 변할 때 알아서 변하는 것을 보실 수 있을 것 입니다.
초안으로 작성해본 코드를 첨부했습니다. 참고하시어 리팩토링 하면 더 좋은 코드가 될 것 같습니다
import { create } from 'zustand';
import type { CartItem } from '../types/cart';
import cartItems from '../constants/cartItems';
type CartStore = {
cartItems: CartItem[];
increase: (id: string) => void;
decrease: (id: string) => void;
removeItem: (id: string) => void;
clearCart: () => void;
};
// 1. 스토어는 cartItems만 관리합니다.
export const useCartStore = create<CartStore>((set) => ({
cartItems,
increase: (id) =>
set((state) => ({
cartItems: state.cartItems.map((item) =>
item.id === id ? { ...item, amount: item.amount + 1 } : item
),
})),
decrease: (id) =>
set((state) => ({
cartItems: state.cartItems
.map((item) => (item.id === id ? { ...item, amount: item.amount - 1 } : item))
.filter((item) => item.amount >= 1),
})),
removeItem: (id) =>
set((state) => ({
cartItems: state.cartItems.filter((item) => item.id !== id),
})),
clearCart: () => set({ cartItems: [] }),
}));
// 계산 전용 Selector 훅을 분리합니다.
export const useCartTotals = () => {
// 스토어에서 cartItems의 변경만 구독합니다.
const cartItems = useCartStore((state) => state.cartItems);
// 데이터가 바뀔 때만 총수량과 총액을 계산합니다.
const amount = cartItems.reduce((sum, item) => sum + item.amount, 0);
const total = cartItems.reduce((sum, item) => sum + Number(item.price) * item.amount, 0);
return { amount, total };
};
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
✅ 워크북 체크리스트
✅ 컨벤션 체크리스트
📌 주안점