summaryrefslogtreecommitdiff
path: root/storefront/pages/cart.js
diff options
context:
space:
mode:
Diffstat (limited to 'storefront/pages/cart.js')
-rw-r--r--storefront/pages/cart.js101
1 files changed, 101 insertions, 0 deletions
diff --git a/storefront/pages/cart.js b/storefront/pages/cart.js
new file mode 100644
index 0000000..fa625a9
--- /dev/null
+++ b/storefront/pages/cart.js
@@ -0,0 +1,101 @@
+import { useCallback, useEffect, useState } from "react"
+import { medusaClient } from "../lib/medusa-client"
+import { formatAmount } from "../lib/format"
+import { getStoredCartId, clearStoredCartId } from "../lib/storefront"
+
+export default function CartPage() {
+ const [cart, setCart] = useState(null)
+ const [status, setStatus] = useState("")
+ const [isLoading, setIsLoading] = useState(true)
+
+ const loadCart = useCallback(async () => {
+ const storedCartId = getStoredCartId()
+ if (!storedCartId) {
+ setCart(null)
+ setIsLoading(false)
+ return
+ }
+
+ try {
+ const { cart: fetchedCart } = await medusaClient.carts.retrieve(storedCartId)
+ setCart(fetchedCart)
+ } catch (error) {
+ clearStoredCartId()
+ setCart(null)
+ } finally {
+ setIsLoading(false)
+ }
+ }, [])
+
+ useEffect(() => {
+ loadCart()
+ }, [loadCart])
+
+ const handleRemove = async (lineItemId) => {
+ if (!cart) {
+ return
+ }
+ setStatus("")
+ try {
+ await medusaClient.carts.lineItems.delete(cart.id, lineItemId)
+ await loadCart()
+ } catch (error) {
+ setStatus("Impossible de retirer l'article.")
+ }
+ }
+
+ if (isLoading) {
+ return <p>Chargement du panier...</p>
+ }
+
+ if (!cart || !cart.items?.length) {
+ return <p>Votre panier est vide.</p>
+ }
+
+ return (
+ <div style={{ maxWidth: "720px", margin: "0 auto" }}>
+ <h1>Panier</h1>
+ {status && <p>{status}</p>}
+ <div style={{ display: "grid", gap: "1rem", marginTop: "1rem" }}>
+ {cart.items.map((item) => (
+ <div
+ key={item.id}
+ style={{
+ border: "1px solid #ccc",
+ borderRadius: "8px",
+ padding: "1rem",
+ display: "flex",
+ justifyContent: "space-between",
+ gap: "1rem",
+ }}
+ >
+ <div>
+ <strong>{item.title}</strong>
+ <p>Quantité : {item.quantity}</p>
+ <p>
+ {formatAmount(item.unit_price, cart.region?.currency_code || "eur")}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => handleRemove(item.id)}
+ style={{
+ border: "1px solid #ccc",
+ background: "#fff",
+ borderRadius: "6px",
+ padding: "0.4rem 0.8rem",
+ cursor: "pointer",
+ height: "fit-content",
+ }}
+ >
+ Retirer
+ </button>
+ </div>
+ ))}
+ </div>
+ <p style={{ marginTop: "1.5rem", fontWeight: 600 }}>
+ Total : {formatAmount(cart.total, cart.region?.currency_code || "eur")}
+ </p>
+ </div>
+ )
+}