Build a cart with shared state
Build a small shop where a header badge, a product list and a cart all show the same data, without any of them calling the others. It uses Store for the data and Component for every view.
What you will build
- A badge in the header showing how many items are in the cart.
- A product list with an Add button on each product.
- A cart listing what was added, with a total.
Each view is bound to one store. A click changes the store, and every view that shows the changed data updates itself. The Store example is a fuller version of the same shop.
1. The page
<script type="module" src="main.js" data-id="vUX" data-library-root="/lib/vUX/"></script>
<header>Shop <span id="badge"></span></header>
<ul id="products"></ul>
<ul id="cart"></ul>
<p id="total"></p>
<template id="badgeTpl"><b data-v-field="count"></b></template>
<template id="productTpl">
<li>
<span data-v-field="name"></span>
<span data-v-field="price"></span>
<button data-v-on="click:add">Add</button>
</li>
</template>
<template id="cartTpl">
<li><span data-v-field="name"></span> x <span data-v-field="qty"></span></li>
</template>
<template id="totalTpl"><span>Total: <b data-v-field="total"></b></span></template>2. The store
The store holds only what changes: the cart. The product catalogue never changes, so it stays a plain constant.
import { Store } from "/lib/vUX/vUX-store.js";
import { Component } from "/lib/vUX/vUX-component.js";
const PRODUCTS = [
{ id: 1, name: "Mug", price: 6500 },
{ id: 2, name: "Kettle", price: 38000 },
{ id: 3, name: "Apron", price: 14500 }
];
const byId = new Map(PRODUCTS.map((p) => [p.id, p]));
const cart = new Store({ items: [] }); // [{ id, qty }]
cart.config.computed = {
count: (s) => s.items.reduce((n, i) => n + i.qty, 0),
total: (s) => s.items.reduce((t, i) => t + i.qty * byId.get(i.id).price, 0)
};
cart.initialize();count and total are computed fields. They are worked out after every change, and you can read and watch them like any other field.
Important
Every field must be declared in the initial state. cart.set({ itms: [] }) throws, so a typo shows up at once instead of creating a field nothing reads.
3. One function that writes
All the buttons will go through one function, so the cart's rules live in one place. It uses the updater form of set(), because the new array depends on the current one:
function add(id){
cart.set((s) => {
const line = s.items.find((i) => i.id === id);
return {
items: line
? s.items.map((i) => i.id === id ? { id, qty: i.qty + 1 } : i)
: [...s.items, { id, qty: 1 }]
};
});
}Warning
Always build a new array. The store compares values by identity, so pushing into the array it holds changes nothing as far as the store is concerned.
4. Bind the badge and the total
bind() connects a Component instance to the store. The function maps the store to the fields the template shows. The last argument lists the store fields it depends on, so it only runs when one of them changes:
const badge = new Component($$.ss("#badgeTpl"));
badge.initialize();
cart.bind(badge.mount($$.ss("#badge"), {}), (s) => ({ count: s.count }), ["count"]);
const total = new Component($$.ss("#totalTpl"));
total.initialize();
cart.bind(total.mount($$.ss("#total"), {}), (s) => ({ total: s.total.toLocaleString() }), ["total"]);Both apply once straight away, so the badge shows 0 before anything is added.
5. Bind the two lists
bindList() keeps a keyed list in step with the store. Rows are matched by config.key, so a row that stays in the list keeps its element:
const product = new Component($$.ss("#productTpl"));
product.config.key = "id";
product.config.handlers = { add: (data) => add(data.id) };
product.initialize();
cart.bindList(product, $$.ss("#products"),
() => PRODUCTS.map((p) => ({ id: p.id, name: p.name, price: p.price.toLocaleString() })), ["items"]);
const row = new Component($$.ss("#cartTpl"));
row.config.key = "id";
row.initialize();
cart.bindList(row, $$.ss("#cart"),
(s) => s.items.map((i) => ({ id: i.id, name: byId.get(i.id).name, qty: i.qty })), ["items"]);The product list does not depend on the cart yet; giving it ["items"] means you can later show "in cart" on each product without changing the binding.
6. Try it
Click Add on a product. One set() runs, and:
- the badge count goes up (because
countchanged), - the cart gains a row or a row's quantity goes up (because
itemschanged), - the total updates (because
totalchanged).
None of these views knows the others exist. Adding a fourth view is one more bind().
Going further
- Watch changes yourself.
cart.subscribe((state, changed) => console.log(changed))logs every change. - Several changes at once.
cart.batch(() => { ... })makes severalset()calls and tells everyone once. - Keep the cart across reloads. See Patterns in the Store reference.
- Clean up.
bind()andbindList()return a function that disconnects the binding; call it when the view goes. See Lifecycle and teardown.