invix_test_task/web/app/cart/page.tsx

59 lines
1.5 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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>}
</>
);
}