🛒 Shopping Cart

Complex state management with derived calculations

Shopping Cart (0 items)

Available Products

TypeScript Book

$29.99

React Hooks Guide

$19.99

Next.js Manual

$39.99

State Management Guide

$24.99

Cart Items

Your cart is empty

Order Summary

Items (0):$0.00

Total:$0.00

Current Store State:

{
  "totalItems": 0,
  "subtotal": 0,
  "discountCode": "",
  "hasDiscount": false,
  "itemCount": 0
}

🏗️ Store Architecture

This shopping cart demonstrates advanced NextTinyRXStore features:

  • Complex State: Arrays, objects, and primitives in one store
  • Derived Calculations: Total items, subtotal, and discount logic
  • Performance Optimization: Only re-render components that need updates
  • Type Safety: Full TypeScript support for all operations

Store Definition

const cartStore = createFieldStore({
  items: [] as CartItem[],
  discountCode: "",
  shippingAddress: null as Address | null,
})
.derived("totalItems", ["items"], 
  ({ items }) => items.reduce((sum, item) => 
    sum + item.quantity, 0)
)
.derived("subtotal", ["items"], 
  ({ items }) => items.reduce((sum, item) => 
    sum + (item.price * item.quantity), 0)
)
.derived("hasDiscount", ["discountCode"], 
  ({ discountCode }) => discountCode.length > 0
);

Complex Operations

const addItem = (product: Product) => {
  const existingItem = items.find(
    item => item.id === product.id
  );

  if (existingItem) {
    cartStore.setters.setItems(
      items.map(item =>
        item.id === product.id
          ? { ...item, quantity: item.quantity + 1 }
          : item
      )
    );
  } else {
    cartStore.setters.setItems([
      ...items, 
      { ...product, quantity: 1 }
    ]);
  }
};

Performance Optimizations

// Only re-render when specific fields change
const { items, totalItems, subtotal } = cartStore.useFields([
  "items", "totalItems", "subtotal"
]);

// Cart header only watches totalItems - won't re-render on item changes
const totalItems = cartStore.useField("totalItems");

// Discount section only watches discount-related fields
const { discountCode, hasDiscount } = cartStore.useFields([
  "discountCode", "hasDiscount"
]);

⚡ Performance Benefits

Granular Updates:

  • Cart total updates only when items change
  • Discount UI only updates when discount code changes
  • Individual items only re-render when their data changes

Efficient Calculations:

  • Derived fields are cached until dependencies change
  • Complex calculations run only when necessary
  • Reactive streams prevent duplicate computations