안녕하세요. 이번에는 Fake Store Api를 활용하여 쇼핑몰 아이템 리스트를 불러오고 그것을 이용하여 장바구니에 넣고 삭제하는 기능을 타입스크립트와 리액트를 이용해서 만들어보았습니다.
깃허브 url - https://github.com/zlzlzlmo/shopping_cart-with-react-ts
UI는 material ui를 활용하였습니다.
const getProducts = async (): Promise<CartItemType[]> => {
return await (await fetch("https://fakestoreapi.com/products")).json();
};
const { data, isLoading, error } = useQuery("products", getProducts);
export type CartItemType = {
id: number;
category: string;
description: string;
image: string;
price: number;
title: string;
amount: number;
};
const [cartItems, setCartItems] = useState<CartItemType[]>([]);
const handleAddToCart = (clickedItem: CartItemType) => {
setCartItems((prev) => {
const isItemInCart = prev.find((item) => item.id === clickedItem.id);
if (isItemInCart) {
return prev.map((item) =>
item.id === clickedItem.id
? { ...item, amount: item.amount + 1 }
: item
);
}
return [...prev, { ...clickedItem, amount: 1 }];
});
};
코드 설명
const getTotalItems = (items: CartItemType[]) => {
return items.reduce((ack: number, item) => {
return ack + item.amount;
}, 0);
};
코드 설명
const handleRemoveFromCart = (id: number) => {
setCartItems((prev) =>
prev.reduce((ack, item) => {
if (item.id === id) {
if (item.amount === 1) return ack;
return [...ack, { ...item, amount: item.amount - 1 }];
} else {
return [...ack, item];
}
}, [] as CartItemType[])
);
};
코드 설명
{cartItems.length === 0 ? <p>현재 등록된 상품이 없습니다.</p> : null}
타입스크립트와 리액트의 조합을 이용하여 간단한 어플리케이션을 만들어보았습니다. 아직 많이 낯설고 미숙하지만, 지속적으로 연습하다보면 숙달될것이라고 믿고있습니다. 앞으로 지속적인 연습을 통하여 리액트와 타입스크립트 꿀조합을 능숙하게 사용하는 날이 오면 좋겠습니다.
감사합니다