React로 장바구니 만들기

이번에는 React JS를 이용해 장바구니를 만들어보자.

컴포넌트 구성

const ProductList = ({ productList, handleProductItemClick }) => {
    if (productList === undefined || productList.length === 0) {
        return '상품이 없습니다.';
    }
    return (
        <>
            <section id="product-list">
                <div
                    id="product-card-grid"
                    className="grid gap-4 auto-cols-fr grid-cols-2 md:grid-cols-4"
                >
                    {productList?.map((item) => (
                        <ProductItem
                            key={item.id}
                            id={item.id}
                            imgSrc={item.imgSrc}
                            name={item.name}
                            price={item.price}
                            handleProductItemClick={handleProductItemClick}
                        />
                    ))}
                </div>
            </section>
        </>
    );
};

비동기 API 요청 모킹하기

useEffect(() => {
        const fetchProductData = async () => {
            const result = await getProductList();
            setProductList(result);
        };
        fetchProductData();
}, []);

const request = async (url) => {
    try {
        const response = await fetch(url);
        if (response.ok) {
            const data = await response.json();
            return data;
        }
        throw response.json();
    } catch (e) {
        console.log(e);
    }
};

const getProductList = async () => {
    const result = await request('./productData.json');
    return result;
};

상품 목록 렌더링하기

장바구니 토글 기능

<App>
    <ProductList />
    <CartList />
</App>
const handleOpenCloseCartToolpane = () => {
        setCartToolpaneOpen((prev) => !prev);
};

장바구니 추가 기능

 const handleProductItemClick = (e) => {
        // 장바구니 토글
        handleOpenCloseCartToolpane();
        const productId = e.target.dataset.productid;
        addCartItem(parseInt(productId));
};

    const addCartItem = (id) => {
        const selectedItem = productList.find((item) => item.id === id);
        const idx = cartList.findIndex((item) => item.id === id);
        if (idx === -1) {
            setCartList((prev) => [...prev, { ...selectedItem, count: 1 }]);
        } else {
            cartList[idx].count += 1;
            setCartList([...cartList]);
        }
};

장바구니 상품 삭제 기능

const handleRemoveItem = () => {
        const newCratList = cartList.filter((item) => item.id !== id);
        setCartList([...newCratList]);
};

Web Storage API를 사용한 장바구니 데이터 저장 기능

// 장바구니 데이터 저장
const saveCartList = (e) => {
    e.preventDefault();
    localStorage.setItem('cartList', JSON.stringify(cartList));
};

// 장바구니 데이터 로드
useEffect(() => {
    setCartList(JSON.parse(localStorage.getItem('cartList')));
}, [setCartList]);

완성본

완성본 보러가기

끝!