Cart Management

Updated 8 July 2026

The shopping cart uses WooCommerce Store API with session-based cart tokens. This section covers adding items, updating quantities, and managing the cart state.

Cart Architecture

The cart uses WooCommerce Store API with session-based cart tokens:

Adding Items to Cart

"use client";

import { useCart } from "@/contexts/CartContext"; // Import Cart context

const { addToCart } = useCart(); // Get add to cart function from cart context

 addToCart(productId, 1)}> // Add to cart with quantity 1 to the product with the given product id
  Add to Cart

Variable Products

await addToCart(productId, quantity, {
  attributes: [
    { id: 1, option: "Red" },
    { id: 2, option: "Large" }      
  ]
});

Updating Cart Quantities

const { updateQuantity } = useCart(); // Get update quantity function from cart context

 updateQuantity(itemKey, quantity + 1)}>+ // Update quantity of the item with the given key to the new quantity
 updateQuantity(itemKey, quantity - 1)}>- // Update quantity of the item with the given key to the new quantity

Removing Items from Cart

const { removeItem } = useCart(); // Get remove item function from cart context

 removeItem(itemKey)}>Remove // Remove item with the given key from the cart

Cart Data Structure

{ // Cart data including items and totals        
  items: [{
    key: "item-key",
    product_id: 123,
    name: "Product",
    quantity: 2,
    prices: { price: "29.99" },
    totals: { line_total: "59.98" }
  }],
  totals: {
    total_items: "59.98",
    total_shipping: "5.00",
    total_price: "64.98"
  }
}

Displaying Cart Items

const { cartData } = useCart(); // Get cart data from cart context

{cartData.items.map(item => (
   // Display item with the given key
    {item.name} // Display item name
    ${item.totals.line_total} × {item.quantity} // Display item total and quantity
  
))}

Displaying Cart Totals

const { cartData } = useCart(); // Get cart data from cart context
const { totals } = cartData;

Subtotal: ${totals.total_items} // Display subtotal
Shipping: ${totals.total_shipping} // Display shipping
Total: ${totals.total_price} // Display total

Checking if Product is in Cart

const { isInCart } = useCart(); // Get isInCart function from cart context

{isInCart(productId) ? "In Cart" : "Add to Cart"} // Check if product is in cart with the given product id

Clearing the Cart

const { clearCart } = useCart(); // Get clear cart function from cart context

clearCart()}>Clear Cart // Clear cart

Cart Persistence

The cart persists across sessions using cart tokens:

Optimistic Updates

The Cart Context uses optimistic updates for better UX:

Benefits: Optimistic updates make the app feel faster and more responsive, even with network latency.

Error Handling

try {
  await addToCart(productId, 1); // Add product to cart with the given product id and quantity 1
} catch (error) {
  console.error("Error:", error);
  // Show error message
}

Best Practices