59 lines
1.5 KiB
TypeScript
59 lines
1.5 KiB
TypeScript
"use client";
|
||
|
||
import Link from "next/link";
|
||
import { useEffect, useState } from "react";
|
||
|
||
import type { Cart } from "@/lib/types";
|
||
|
||
export default function CartPage() {
|
||
const [cart, setCart] = useState<Cart | null>(null);
|
||
const [error, setError] = useState("");
|
||
|
||
async function load() {
|
||
const response = await fetch("/backend/cart", { credentials: "include", cache: "no-store" });
|
||
if (!response.ok) {
|
||
setError("Не удалось загрузить корзину");
|
||
return;
|
||
}
|
||
setCart(await response.json());
|
||
}
|
||
|
||
useEffect(() => {
|
||
void load();
|
||
}, []);
|
||
|
||
async function remove(productId: number) {
|
||
const response = await fetch(`/backend/cart/items/${productId}`, {
|
||
method: "DELETE",
|
||
credentials: "include",
|
||
});
|
||
if (response.ok) {
|
||
setCart(await response.json());
|
||
}
|
||
}
|
||
|
||
if (error) {
|
||
return <p className="error">{error}</p>;
|
||
}
|
||
if (!cart) {
|
||
return <p>Загрузка…</p>;
|
||
}
|
||
|
||
return (
|
||
<>
|
||
<h1>Корзина</h1>
|
||
{cart.items.length === 0 && <p>Пока пусто.</p>}
|
||
{cart.items.map((item) => (
|
||
<p key={item.product_id}>
|
||
{item.title} × {item.qty} = {item.line_total} ₽{" "}
|
||
<button type="button" onClick={() => void remove(item.product_id)}>
|
||
Убрать
|
||
</button>
|
||
</p>
|
||
))}
|
||
<p>Итого: {cart.total} ₽</p>
|
||
{cart.items.length > 0 && <Link href="/checkout">Оформить заказ</Link>}
|
||
</>
|
||
);
|
||
}
|