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:
- Cart Token: Generated by WooCommerce, stored in httpOnly cookies
- Cart Items: Stored server-side in WooCommerce session
- Optimistic Updates: UI updates immediately, syncs with server
- Persistence: Cart persists across page refreshes and browser sessions
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 CartVariable 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 quantityRemoving Items from Cart
const { removeItem } = useCart(); // Get remove item function from cart context
removeItem(itemKey)}>Remove // Remove item with the given key from the cartCart 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 totalChecking 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 idClearing the Cart
const { clearCart } = useCart(); // Get clear cart function from cart context
clearCart()}>Clear Cart // Clear cartCart Persistence
The cart persists across sessions using cart tokens:
- Cart token is stored in httpOnly cookies
- Token is sent with every cart request
- Cart data is stored server-side in WooCommerce
- Cart expires after period of inactivity (configurable)
Optimistic Updates
The Cart Context uses optimistic updates for better UX:
- UI updates immediately when user interacts
- Request sent to server in background
- If request fails, UI reverts to previous state
- If request succeeds, UI reflects server state
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
- Show Loading States: Indicate when cart operations are in progress
- Handle Errors Gracefully: Display user-friendly error messages
- Use Optimistic Updates: Update UI immediately for better UX
- Validate Quantities: Ensure quantities are positive numbers
- Check Stock Availability: Verify product is in stock before adding
- Debounce Updates: Avoid rapid-fire quantity updates
Next Steps: Learn about the Checkout Process to complete the purchase flow.