Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Projects and Practice

Project: A Shopping Cart with Multiple Stores

Build a shopping cart with three cooperating Pinia stores: a product catalog, a cart with coupons and totals, and a checkout flow with stock checks, errors and persistence.

A todo list needs one store. Real features rarely do. A shop has a catalog, a cart and a checkout, and they must cooperate without being tangled. This project shows how to split responsibilities across stores, let stores use each other safely and keep money math correct.

Design: who owns what

Store Owns Does not own
products the list of products, stock levels what is in the cart
cart lines { productId, qty }, coupon prices (looked up from products)
orders placed orders and checkout status cart lines (it reads and clears them)

A key rule: the cart stores ids and quantities, not copies of product data. The price comes from the products store at read time, so a price change shows up everywhere and nothing goes stale.

flowchart TD
  P["products store"]
  C["cart store"]
  O["orders store"]
  C -->|"reads price, stock"| P
  O -->|"reads lines, clears cart"| C
  O -->|"reduces stock"| P

Dependencies point one way: orders depends on cart and products; cart depends on products; products depends on nothing.

Avoid cycles: if products also imported cart, importing either would be a puzzle. One-directional dependencies keep the design simple.

Money: use whole cents

Floating point numbers are bad at money (0.1 + 0.2 is 0.30000000000000004). Store prices as integers in cents and format only for display:

JavaScript
const money = (cents) => (cents / 100).toLocaleString("en-US", { style: "currency", currency: "USD" });

The stores

JavaScript
const useProductsStore = defineStore("products", {
  state: () => ({
    items: [
      { id: 1, name: "Notebook", price: 450, stock: 5 },
      { id: 2, name: "Pen", price: 120, stock: 20 },
      { id: 3, name: "Backpack", price: 4900, stock: 2 },
    ],
  }),
  getters: {
    byId: (state) => (id) => state.items.find((p) => p.id === id),
  },
  actions: {
    reduceStock(id, qty) { this.byId(id).stock -= qty; },
  },
});

The byId getter returns a function. Getters that take arguments are not cached per argument, but they are handy and the lookup is cheap.

JavaScript
const useCartStore = defineStore("cart", {
  state: () => ({ lines: [], coupon: null }),
  getters: {
    detailed() {
      const products = useProductsStore();
      return this.lines.map((l) => {
        const p = products.byId(l.productId);
        return { ...l, name: p.name, price: p.price, stock: p.stock, subtotal: p.price * l.qty };
      });
    },
    subtotal() { return this.detailed.reduce((sum, l) => sum + l.subtotal, 0); },
    discount() { return this.coupon === "SAVE10" ? Math.round(this.subtotal * 0.1) : 0; },
    total() { return this.subtotal - this.discount; },
    count: (state) => state.lines.reduce((n, l) => n + l.qty, 0),
  },
  actions: {
    add(productId) {
      const stock = useProductsStore().byId(productId).stock;
      const line = this.lines.find((l) => l.productId === productId);
      if (line) { if (line.qty < stock) line.qty++; }
      else if (stock > 0) this.lines.push({ productId, qty: 1 });
    },
    setQty(productId, qty) {
      if (qty <= 0) this.lines = this.lines.filter((l) => l.productId !== productId);
      else this.lines.find((l) => l.productId === productId).qty = qty;
    },
    applyCoupon(code) { this.coupon = code.trim().toUpperCase() === "SAVE10" ? "SAVE10" : null; return this.coupon !== null; },
  },
});

The cart limits quantity to stock. That rule is inside add, so the button cannot bypass it.

JavaScript
const useOrdersStore = defineStore("orders", {
  state: () => ({ placed: [], status: "idle", error: null }),
  actions: {
    async checkout() {
      const cart = useCartStore();
      const products = useProductsStore();
      if (cart.lines.length === 0) { this.error = "Your cart is empty."; return false; }
      this.status = "paying"; this.error = null;
      try {
        await new Promise((r) => setTimeout(r, 500));          // pretend payment
        cart.detailed.forEach((l) => products.reduceStock(l.productId, l.qty));
        this.placed.push({ id: this.placed.length + 1, total: cart.total, lines: cart.count });
        cart.$reset();
        this.status = "done";
        return true;
      } catch (e) {
        this.status = "idle"; this.error = e.message; return false;
      }
    },
  },
});

cart.$reset() clears lines and coupon in one call, back to the initial state.

The running shop

Add items (note the limit when you reach the stock), try the coupon SAVE10 and check out. Stock drops and the order appears.

Shop: products, cart and orders stores

What this design buys you

  • Single source of truth. Price and stock live only in products. The cart cannot show an old price.
  • Rules next to data. Stock limits are in cart.add, order logic in orders.checkout.
  • Cheap testing. Seed products with $patch, call cart.add and assert cart.total, no component needed.
  • Easy persistence. Persist only cart.lines and cart.coupon (not prices), as in the persistence lesson with pick: ["lines", "coupon"].

Edge cases to think about

  1. A product's stock drops (someone else bought it) while it sits in a cart. The detailed getter could clamp quantity, and checkout should re-check stock on the server. Never trust the browser for prices or stock; this client store is a view of server truth.
  2. A coupon that depends on cart contents must be re-evaluated whenever lines change, which is why discount is a getter and not state.
  3. A failed payment must leave the cart intact. Notice that $reset() runs only after the payment succeeded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the cart store product ids and quantities instead of copies of products?

    Copies get out of date. Looking up the product at read time keeps data consistent.
  2. 2. Why are prices stored as integer cents?

    0.1 + 0.2 is not exactly 0.3 in floating point; whole cents are exact.
  3. 3. Which store dependency direction avoids cycles here?

    A one-way chain of dependencies is easy to reason about and import.
  4. 4. What does cart.$reset() do after checkout?

    $reset re-runs the state function and patches the result in for that store.

Summary

  • Split by responsibility: catalog, cart, orders; keep dependencies one-directional.
  • Store ids and quantities; derive names, prices and totals in getters.
  • Use integer cents for money.
  • Keep business rules in actions; reset the cart only after success.
  • The server, not the client store, is the authority on price and stock.

Next: Project: Auth Store and Route Guards