Shared signals, computed totals, localStorage persistence, and batch updates
// store/cart.ts — shared across components
export const cartItems = signal([]);
export const subtotal = computed(() =>
cartItems.value.reduce((sum, i) => sum + i.price * i.qty, 0)
);
export const tax = computed(() => subtotal.value * 0.08);
export const total = computed(() => subtotal.value + tax.value);
export const itemCount = computed(() =>
cartItems.value.reduce((n, i) => n + i.qty, 0)
);
// Persist to localStorage
effect(() => {
localStorage.setItem('cart', JSON.stringify(cartItems.value));
});
// Restore on load
const saved = localStorage.getItem('cart');
if (saved) cartItems.value = JSON.parse(saved);
// Batch updates avoid intermediate re-renders
batch(() => {
addItem(product1);
addItem(product2);
addItem(product3);
});