E-commerceStorefront Recipes

Storefront Recipes

This collection of common patterns helps you build essential e-commerce features using the Aerocall API.

Recipe 1: The “Add to Cart” Button

Use this pattern to seamlessly add items without blocking the UI.

The Concept

  1. Optimistic UI: Immediately provide feedback (e.g., button spins).
  2. API Call: Send the request to POST /cart/:id/items.
  3. Sync: Update the global cart state with the response.

Example Code (JavaScript/React)

async function addToCart(productId, quantity = 1) {
  setLoading(true);
  try {
    const cartId = localStorage.getItem('cartId');
    const response = await fetch(\`/api/v1/ecommerce/cart/\${cartId}/items\`, {
      method: 'POST',
      body: JSON.stringify({ productId, quantity }),
      headers: { 'Content-Type': 'application/json' }
    });
    
    if (!response.ok) throw new Error('Failed to add');
    const updatedCart = await response.json();
    
    // Update global context/state
    updateCartState(updatedCart);
    showToast('Added to cart!');
  } catch (error) {
    console.error(error);
    showToast('Error adding item', 'error');
  } finally {
    setLoading(false);
  }
}

Recipe 2: Dynamic Category Navigation

Build a menu that automatically updates when you add new categories in the Admin Panel.

The Concept

Fetch the full category tree once on app load (or build time for SSG) and recursive render links.

Data Fetching

// Fetch categories for navigation
const categories = await fetch('/api/v1/ecommerce/categories').then(res => res.json());
 
// Recursive component (React example)
function CategoryMenu({ items }) {
  return (
    <ul>
      {items.map(cat => (
        <li key={cat.id}>
          <a href={\`/category/\${cat.slug}\`}>{cat.name}</a>
          {cat.children && <CategoryMenu items={cat.children} />}
        </li>
      ))}
    </ul>
  );
}

Show “You might also like” based on the current product’s category.

The Query

When viewing a product, use its category_id to fetch peers, excluding the current product.

GET /api/v1/ecommerce/products?category_id=123&exclude=456&limit=4

Recipe 4: Flash Sale Countdown

Create urgency for time-limited coupons or promotions.

The Setup

  1. Create a Coupon in Admin (e.g., “FLASH50”).
  2. Set the Valid Function date.
  3. On the frontend, fetch the coupon details (or hardcode the end date if it’s a global event).

The Component

Use a standard countdown library or setInterval to tick down to the valid_until timestamp.

Recipe 5: Handling Out of Stock

Don’t let users buy what you don’t have.

  1. Check Inventory: The Product API returns inventory.
  2. Disable Button: If inventory <= 0 (and backorders are disabled), gray out the “Add to Cart” button.
  3. Real-time Check: The API will reject the POST /cart request if stock runs out between page load and click. Handle 409 Conflict errors gracefully:
if (response.status === 409) {
  alert("Sorry, this item just went out of stock!");
  refreshProductData(); // Update UI to reflect new stock
}