Skip to main content

Lesson 8 of 9

Mini Project: E-Commerce Cart

Build a complete e-commerce cart system combining Zustand (cart global state with persistence), TanStack Query (product data fetching), and react-hook-form with Zod (checkout form). This mirrors how real production e-commerce applications are built.

55 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

E-Commerce Cart Implementation

E-Commerce Cart Implementation
import { create } from 'zustand';
import { persist, devtools } from 'zustand/middleware';
import { useQuery } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useState } from 'react';

// ---- Types ----
interface Product { id: string; name: string; price: number; image: string; stock: number; }
interface CartItem { productId: string; quantity: number; }

// ---- Zustand Cart Store with Persistence ----
interface CartStore {
  items: CartItem[];
  addItem: (productId: string) => void;
  removeItem: (productId: string) => void;
  setQuantity: (productId: string, qty: number) => void;
  clear: () => void;
}

const useCartStore = create<CartStore>()(
  devtools(persist(
    (set) => ({
      items: [],
      addItem: (productId) => set(state => {
        const existing = state.items.find(i => i.productId === productId);
        return existing
          ? { items: state.items.map(i => i.productId === productId ? { ...i, quantity: i.quantity + 1 } : i) }
          : { items: [...state.items, { productId, quantity: 1 }] };
      }),
      removeItem: (productId) => set(state => ({
        items: state.items.filter(i => i.productId !== productId),
      })),
      setQuantity: (productId, qty) => set(state => ({
        items: qty <= 0
          ? state.items.filter(i => i.productId !== productId)
          : state.items.map(i => i.productId === productId ? { ...i, quantity: qty } : i),
      })),
      clear: () => set({ items: [] }),
    }),
    { name: 'cart' }
  ), { name: 'CartStore' })
);

// ---- Mock API ----
const PRODUCTS: Product[] = [
  { id: 'p1', name: 'Mechanical Keyboard', price: 129.99, image: 'โŒจ๏ธ', stock: 10 },
  { id: 'p2', name: 'HD Webcam', price: 79.99, image: '๐Ÿ“ท', stock: 5 },
  { id: 'p3', name: 'USB-C Hub', price: 49.99, image: '๐Ÿ”Œ', stock: 20 },
];
const fetchProducts = () => new Promise<Product[]>(resolve => setTimeout(() => resolve(PRODUCTS), 500));

// ---- Checkout schema ----
const checkoutSchema = z.object({
  name: z.string().min(2, 'Name required'),
  email: z.string().email('Valid email required'),
  address: z.string().min(5, 'Address required'),
  city: z.string().min(2, 'City required'),
  card: z.string().regex(/^d{16}$/, '16-digit card number'),
});
type CheckoutData = z.infer<typeof checkoutSchema>;

// ---- Product Card ----
function ProductCard({ product }: { product: Product }) {
  const addItem = useCartStore(s => s.addItem);
  const cartItem = useCartStore(s => s.items.find(i => i.productId === product.id));
  return (
    <div style={{ background: '#1e293b', borderRadius: 12, padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ fontSize: 48, textAlign: 'center' }}>{product.image}</div>
      <h3 style={{ margin: 0, fontSize: 15 }}>{product.name}</h3>
      <p style={{ margin: 0, color: '#60a5fa', fontWeight: 700 }}>${product.price.toFixed(2)}</p>
      <button
        onClick={() => addItem(product.id)}
        style={{ background: '#229c6b', border: 'none', color: 'white', padding: '8px 16px', borderRadius: 8, cursor: 'pointer', fontWeight: 600 }}
      >
        {cartItem ? `In Cart (${cartItem.quantity})` : 'Add to Cart'}
      </button>
    </div>
  );
}

// ---- Cart Panel ----
function CartPanel({ products }: { products: Product[] }) {
  const { items, removeItem, setQuantity, clear } = useCartStore();
  const total = items.reduce((sum, item) => {
    const p = products.find(p => p.id === item.productId);
    return sum + (p?.price ?? 0) * item.quantity;
  }, 0);

  if (items.length === 0) return <p style={{ color: '#64748b', textAlign: 'center' }}>Your cart is empty</p>;

  return (
    <div>
      {items.map(item => {
        const product = products.find(p => p.id === item.productId);
        if (!product) return null;
        return (
          <div key={item.productId} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: '1px solid #334155' }}>
            <span style={{ fontSize: 24 }}>{product.image}</span>
            <div style={{ flex: 1 }}>
              <p style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>{product.name}</p>
              <p style={{ margin: 0, fontSize: 12, color: '#94a3b8' }}>${product.price}</p>
            </div>
            <input
              type="number"
              min={0}
              value={item.quantity}
              onChange={e => setQuantity(item.productId, Number(e.target.value))}
              style={{ width: 48, background: '#334155', border: 'none', color: 'white', padding: '4px 8px', borderRadius: 6, textAlign: 'center' }}
            />
            <button onClick={() => removeItem(item.productId)} style={{ background: 'transparent', border: 'none', color: '#ef4444', cursor: 'pointer', fontSize: 18 }}>โœ•</button>
          </div>
        );
      })}
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16, paddingTop: 12, borderTop: '1px solid #334155' }}>
        <strong>Total</strong>
        <strong style={{ color: '#60a5fa' }}>${total.toFixed(2)}</strong>
      </div>
      <button onClick={clear} style={{ marginTop: 8, width: '100%', background: 'transparent', border: '1px solid #334155', color: '#94a3b8', padding: '8px', borderRadius: 8, cursor: 'pointer', fontSize: 13 }}>
        Clear Cart
      </button>
    </div>
  );
}

// ---- Checkout Form ----
function CheckoutForm({ onSuccess }: { onSuccess: () => void }) {
  const clear = useCartStore(s => s.clear);
  const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<CheckoutData>({
    resolver: zodResolver(checkoutSchema),
  });

  async function onSubmit(data: CheckoutData) {
    await new Promise(r => setTimeout(r, 1500)); // simulate API
    clear();
    onSuccess();
  }

  const inputStyle = { width: '100%', background: '#334155', border: '1px solid #475569', color: 'white', padding: '8px 12px', borderRadius: 8, fontSize: 13, boxSizing: 'border-box' as const };
  const errorStyle = { color: '#f87171', fontSize: 12, marginTop: 2 };

  return (
    <form onSubmit={handleSubmit(onSubmit)} style={{ display: 'flex', flexDirection: 'column' as const, gap: 12 }}>
      {[
        { name: 'name' as const, label: 'Full Name', type: 'text' },
        { name: 'email' as const, label: 'Email', type: 'email' },
        { name: 'address' as const, label: 'Address', type: 'text' },
        { name: 'city' as const, label: 'City', type: 'text' },
        { name: 'card' as const, label: 'Card Number (16 digits)', type: 'text' },
      ].map(field => (
        <div key={field.name}>
          <label style={{ fontSize: 12, color: '#94a3b8', display: 'block', marginBottom: 4 }}>{field.label}</label>
          <input {...register(field.name)} type={field.type} style={inputStyle} />
          {errors[field.name] && <p style={errorStyle}>{errors[field.name]?.message}</p>}
        </div>
      ))}
      <button
        type="submit"
        disabled={isSubmitting}
        style={{ background: '#10b981', border: 'none', color: 'white', padding: '12px', borderRadius: 8, cursor: 'pointer', fontWeight: 700, fontSize: 15 }}
      >
        {isSubmitting ? 'Processing...' : 'Place Order'}
      </button>
    </form>
  );
}

// ---- Main App ----
export default function ECommerceApp() {
  const [view, setView] = useState<'shop' | 'cart' | 'checkout' | 'success'>('shop');
  const { data: products = [], isLoading } = useQuery({ queryKey: ['products'], queryFn: fetchProducts });
  const itemCount = useCartStore(s => s.items.reduce((sum, i) => sum + i.quantity, 0));

  const bg = { background: '#0f172a', minHeight: '100vh', color: 'white', fontFamily: 'system-ui', padding: 20 };

  if (isLoading) return <div style={{ ...bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>Loading products...</div>;

  if (view === 'success') return (
    <div style={{ ...bg, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', gap: 16 }}>
      <p style={{ fontSize: 64 }}>โœ…</p>
      <h2>Order Placed Successfully!</h2>
      <button onClick={() => setView('shop')} style={{ background: '#229c6b', border: 'none', color: 'white', padding: '10px 24px', borderRadius: 8, cursor: 'pointer', fontWeight: 600 }}>
        Continue Shopping
      </button>
    </div>
  );

  return (
    <div style={bg}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1 style={{ margin: 0, fontSize: 22, cursor: 'pointer' }} onClick={() => setView('shop')}>๐Ÿ›๏ธ TechStore</h1>
        <div style={{ display: 'flex', gap: 8 }}>
          {(['shop', 'cart'] as const).map(v => (
            <button key={v} onClick={() => setView(v)} style={{ background: view === v ? '#229c6b' : '#1e293b', border: 'none', color: 'white', padding: '8px 16px', borderRadius: 8, cursor: 'pointer', textTransform: 'capitalize', fontWeight: 600 }}>
              {v === 'cart' ? `๐Ÿ›’ Cart (${itemCount})` : '๐Ÿ  Shop'}
            </button>
          ))}
        </div>
      </div>

      {view === 'shop' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 16 }}>
          {products.map(p => <ProductCard key={p.id} product={p} />)}
        </div>
      )}

      {view === 'cart' && (
        <div style={{ maxWidth: 480, margin: '0 auto' }}>
          <h2 style={{ marginTop: 0 }}>Your Cart</h2>
          <CartPanel products={products} />
          {itemCount > 0 && (
            <button onClick={() => setView('checkout')} style={{ marginTop: 16, width: '100%', background: '#10b981', border: 'none', color: 'white', padding: '12px', borderRadius: 8, cursor: 'pointer', fontWeight: 700, fontSize: 15 }}>
              Proceed to Checkout โ†’
            </button>
          )}
        </div>
      )}

      {view === 'checkout' && (
        <div style={{ maxWidth: 480, margin: '0 auto' }}>
          <button onClick={() => setView('cart')} style={{ background: 'transparent', border: 'none', color: '#94a3b8', cursor: 'pointer', marginBottom: 16 }}>โ† Back to Cart</button>
          <h2 style={{ marginTop: 0 }}>Checkout</h2>
          <CheckoutForm onSuccess={() => setView('success')} />
        </div>
      )}
    </div>
  );
}

What This Project Demonstrates

  • Zustand with persist middleware - cart survives page refresh, stored in localStorage with devtools integration
  • Selective selectors - each component subscribes to only its slice of the cart store to minimize re-renders
  • TanStack Query for product data - loading state handled automatically, data cached across component mounts
  • react-hook-form + Zod - type-safe form with per-field validation, server error handling, and async submission with loading state
  • State co-location - view state is local to App (it doesn't need to be global), cart is Zustand (truly global), products are TanStack Query (server state)
  • Derived values - `total` and `itemCount` computed from cart items + products without storing redundant state

Tip

Tip

Practice Mini Project ECommerce Cart in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for Mini Project: E-Commerce Cart

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project ECommerce Cart from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project ECommerce Cart is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • Build a complete e-commerce cart system combining Zustand (cart global state with persistence), TanStack Query (product data fetching), and react-hook-form with Zod (checkout form).
  • Zustand with persist middleware - cart survives page refresh, stored in localStorage with devtools integration
  • Selective selectors - each component subscribes to only its slice of the cart store to minimize re-renders
  • TanStack Query for product data - loading state handled automatically, data cached across component mounts

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done