Cart
Mount CartProvider and manage the cart persisted in Storefront API.
The SDK cart is not a separate local store. CartProvider keeps the session
identifier in localStorage and loads the real cart from Storefront API.
1. Mount the provider
import { CartProvider, defineLayout } from "@ecomiq/storefront";
export default defineLayout(({ children, settings }) => (
<CartProvider
storeId={settings.store.id}
currencyCode={settings.store.currency}
>
{children}
</CartProvider>
));The local key is ecomiq:cart:v1:{storeId}, so the session is isolated by store.
Only the identifier is persisted; prices, inventory, and totals are reloaded
from the API.
2. Add a variant
import { useCart } from "@ecomiq/storefront";
export function AddToCartButton({ variantId }: { variantId: string }) {
const { addItem, mutation, error } = useCart();
const isAdding = mutation?.kind === "adding";
return (
<>
<button
type="button"
disabled={isAdding}
onClick={() => void addItem({ variantId, quantity: 1 })}
>
{isAdding ? "Adding…" : "Add to cart"}
</button>
{error ? <p>{error}</p> : null}
</>
);
}variantId is the positive decimal ID returned on a ProductDetail variant.
3. Create the cart page
/cart is not a framework-owned route; create your own UI:
import { definePage, Link, useCart } from "@ecomiq/storefront";
export default definePage({
meta: () => ({ title: "Cart", noIndex: true }),
component: CartPage,
});
function CartPage() {
const { cart, itemCount, loadStatus, removeItem } = useCart();
if (loadStatus === "loading") return <p>Loading…</p>;
if (!cart?.items.length) return <p>Your cart is empty.</p>;
return (
<main>
<h1>{itemCount} products</h1>
{cart.items.map((item) => (
<div key={item.id}>
<span>
{item.title} × {item.quantity}
</span>
<button onClick={() => void removeItem(item.id)}>Remove</button>
</div>
))}
<Link to="/checkout/$checkoutId" params={{ checkoutId: cart.id }}>
Go to checkout
</Link>
</main>
);
}useCart contract
| Field or action | Use |
|---|---|
cart, cartId | Loaded cart and active identifier. |
itemCount | Sum of item quantities. |
loadStatus | loading, ready, or error. |
mutation, error | State of the latest operation. |
addItem | Adds { variantId, quantity }. |
setItemQuantity | Changes a line's quantity. |
removeItem | Removes a line. |
reload | Reloads the cart from the API. |
clearCart | Deletes the current local session. |
To use the included checkout, also add AuthProvider as described in the
checkout guide.