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
- Optimistic UI: Immediately provide feedback (e.g., button spins).
- API Call: Send the request to
POST /cart/:id/items. - 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>
);
}Recipe 3: Related Products
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=4Recipe 4: Flash Sale Countdown
Create urgency for time-limited coupons or promotions.
The Setup
- Create a Coupon in Admin (e.g., âFLASH50â).
- Set the Valid Function date.
- 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.
- Check Inventory: The Product API returns
inventory. - Disable Button: If
inventory <= 0(and backorders are disabled), gray out the âAdd to Cartâ button. - Real-time Check: The API will reject the
POST /cartrequest 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
}