โ† Back to Home

๐Ÿ›’ Shopping Cart - Real E-Commerce Example

Build a complete shopping cart with add/remove, quantities, and auto-calculating totals!

๐Ÿ“š What You'll Learn

  • โœ“Build a real e-commerce shopping cart from scratch
  • โœ“Manage cart items with add/remove/update operations
  • โœ“Auto-calculate totals with computed signals
  • โœ“Handle quantities, pricing, and cart state management

๐ŸŽฎ Try It: Add Products to Cart

Click products to add them, adjust quantities - watch totals update automatically!

0
Items in Cart
$0
Total Price

Products

๐Ÿ’ป

Laptop

$999

๐Ÿ“ฑ

Phone

$699

๐ŸŽง

Headphones

$199

โŒš

Watch

$399

โŒจ๏ธ

Keyboard

$149

๐Ÿ–ฑ๏ธ

Mouse

$79

๐Ÿš€ How It Works

Cart State
const cart = createSignal<CartItem[]>([]);

Single signal holds all cart items

Auto-Computed Totals
const totalPrice = createComputed(() =>
ย ย cart.get().reduce((sum, item) =>
ย ย ย ย sum + item.price * item.quantity, 0)
);

Totals recalculate automatically when cart changes

๐Ÿ’ป Complete Code Example

import { createSignal, createComputed } from 'signalforge/core';
import { useSignalValue } from 'signalforge/react';
import { useState } from 'react';

function ShoppingCart() {
  const [cart] = useState(() => createSignal<CartItem[]>([]));
  
  // Computed totals - auto-update!
  const [totalItems] = useState(() => createComputed(() => 
    cart.get().reduce((sum, item) => sum + item.quantity, 0)
  ));
  
  const [totalPrice] = useState(() => createComputed(() => 
    cart.get().reduce((sum, item) => 
      sum + item.price * item.quantity, 0
    )
  ));
  
  const totalItemsValue = useSignalValue(totalItems);
  const totalPriceValue = useSignalValue(totalPrice);
  
  // Add item to cart
  const addToCart = (product) => {
    const existing = cart.get().find(i => i.id === product.id);
    if (existing) {
      // Increment quantity
      cart.set(cart.get().map(item =>
        item.id === product.id
          ? { ...item, quantity: item.quantity + 1 }
          : item
      ));
    } else {
      // Add new item
      cart.set([...cart.get(), { ...product, quantity: 1 }]);
    }
  };
  
  // Update quantity
  const updateQuantity = (id, delta) => {
    cart.set(cart.get()
      .map(item => item.id === id
        ? { ...item, quantity: item.quantity + delta }
        : item
      )
      .filter(item => item.quantity > 0)
    );
  };
  
  return (
    <div>
      <h2>Cart ({totalItemsValue} items)</h2>
      <h2>Total: 0</h2>
      {/* Cart items */}
    </div>
  );
}

๐Ÿ’ก Best Practices

โœ…
Use computed for calculations

Let SignalForge handle totals automatically.

๐Ÿ›ก๏ธ
Validate quantities

Filter out items with quantity <= 0.

๐Ÿ’พ
Consider persistence

Save cart to localStorage for better UX.

๐ŸŽ“ Next Steps

Master shopping carts? Try these: