const {cart} = useFetchCart();
export default function useFetchCart() {
const store = container.resolve(CartStore);
const [{ cart }] = useStore(store);
useEffectOnce(() => {
store.fetchCart();
});
return { cart };
}
async fetchCart(): Promise<Cart> {
const { data } = await this.instance.get('/cart');
return data;
}
const Container = styled.div`
table {
width: 100%;
}
th, td {
padding: .5rem;
text-align: left;
}
`;
type CartViewProps = {
cart: Cart;
};
export default function CartView({ cart }: CartViewProps) {
if (!cart.lineItems.length) {
return (
<p>장바구니가 비었습니다</p>
);
}
return (
<Container>
<table>
<thead>
<tr>
<th>제품</th>
<th>단가</th>
<th>수량</th>
<th>금액</th>
</tr>
</thead>
<tbody>
{cart.lineItems.map((lineItem) => (
<LineItemView
key={lineItem.id}
lineItem={lineItem}
/>
))}
</tbody>
<tfoot>
<tr>
<th colSpan={3}>
합계
</th>
<td>
{numberFormat(cart.totalPrice)}
원
</td>
</tr>
</tfoot>
</table>
</Container>
);
}
<td>
<Link to={`/products/${lineItem.product.id}`}>
{lineItem.product.name}
</Link>
<Options options={lineItem.options} />
</td>
const Container = styled.div`
margin-top: .5rem;
font-size: 1.4rem;
`;
type OptionsProps = {
options: OrderOption[];
}
export default function Options({ options }: OptionsProps) {
if (!options.length) {
return null;
}
const text = options
.map((option) => `${option.name}: ${option.item.name}`)
.join(', ');
return (
<Container>
({text})
</Container>
);
}
cURL을 이용해서 임의로 장바구니에 상품 담기
curl -X POST https://shop-demo-api-01.fly.dev/cart/line-items \
-H "Content-Type: application/json" \
--data '
{
"productId": "0BV000PRO0001",
"options": [
{
"id": "0BV000OPT0001",
"itemId": "0BV000ITEM001"
},
{
"id": "0BV000OPT0002",
"itemId": "0BV000ITEM005"
}
],
"quantity": 1
}
'