import { useState, useEffect } from "react"; import PageLayout from "../components/PageLayout"; import { getCart, removeFromCart, createOrder } from "../api/index"; export default function Cart() { const [items, setItems] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { getCart() .then((res) => { setItems(res.data); }) .catch(() => setError("Не удалось загрузить товары")) .finally(() => setLoading(false)); }, []); const total = items.reduce((sum, ci) => sum + ci.quantity * ci.item.price, 0); const handleCheckout = async () => { try { await createOrder({ delivery_address: "Уточняется" }); alert("Заказ оформлен"); setItems([]); navigate("/shop"); } catch { alert("Не удалось оформить заказ"); } }; const handleRemove = async (id) => { try { await removeFromCart(id); setItems((prev) => prev.filter((ci) => ci.id !== id)); } catch { alert("Не удалось удалить"); } }; if (loading) { return ( Загрузка товаров ); } return ( Корзина {error && {error}} {items.length === 0 ? ( Корзина пуста ) : ( {items.map((ci) => ( {ci.item.name} {ci.quantity} {ci.item.unit} x {ci.item.price}р. {ci.quantity * ci.item.price} р. handleRemove(ci.id)} className="text-white/40 hover:text-red-400 transition-colors duration-400 text-xl px-2" > x ))} Итого: {total}р. handleCheckout()} > Оформить заказ )} ); }
Загрузка товаров
{error}
Корзина пуста
{ci.item.name}
{ci.quantity} {ci.item.unit} x {ci.item.price}р.