Add interactions.
State → render → derived values.
In this stage, the inventory app becomes a real app. You'll add JavaScript state, CRUD operations, search, category and low-stock filters, live KPI calculations, and localStorage persistence. The new idea here is derived state: stock status is computed from quantity vs reorderLevel, not stored. Same for the KPI totals. Nothing goes stale because nothing is stored twice.
Short answer: One state object (products + filter + query). One render() function that rebuilds the table and KPIs. stockStatus(product) derives the badge from quantity vs reorder. renderKPIs() derives the totals from the product list. localStorage.setItem persists after every change. escapeHtml on every user string. Duplicate SKU rejected at save. Same pattern as the CRM, with inventory-specific derivations.
✅ What you'll build
The shell from Stage 01, now with working data.
Add
Form with SKU, name, category, price, cost, quantity, reorder level. SKU must be unique.
Edit
Click ✎ on any row. Modal pre-fills. Changing quantity re-derives the stock status.
Delete
Click ×. Confirm dialog. Row disappears. KPIs update.
Search
Type in search. Filters by name or SKU. Instant. Empty state on no match.
Filter
All / Electronics / Accessories / Low stock. The low-stock filter shows both low and out-of-stock items.
Live KPIs
Total value (qty × cost), product count, low count, out count. Recomputed on every change.
✅ Derived state — the key idea
Store the truth. Compute the display.
// Source of truth — what's stored
const product = {
quantity: 8,
reorderLevel: 10
};
// Derived — what's shown
function stockStatus(p) {
if (p.quantity === 0) return 'out-of-stock';
if (p.quantity <= p.reorderLevel) return 'low-stock';
return 'in-stock';
}
// Rendered
stockStatus(product); // 'low-stock'
// Change quantity — status changes automatically
product.quantity = 42;
stockStatus(product); // 'in-stock'
product.quantity = 0;
stockStatus(product); // 'out-of-stock'
// ─────────────────────────────────────────────
// BAD: stored status goes stale
const badProduct = {
quantity: 8,
reorderLevel: 10,
status: 'low-stock' // ❌ computed at creation
};
// Later, someone updates quantity:
badProduct.quantity = 42;
// But forgets to update status:
console.log(badProduct.status); // ❌ still 'low-stock'
// The UI shows the wrong badge.
// ─────────────────────────────────────────────
// The same idea for KPIs
function renderKPIs() {
let totalValue = 0;
let low = 0;
let out = 0;
state.products.forEach(function (p) {
totalValue += p.quantity * p.cost; // derived
const s = stockStatus(p); // derived
if (s === 'low-stock') low++;
if (s === 'out-of-stock') out++;
});
document.getElementById('kpi-value').textContent = formatMoney(totalValue);
document.getElementById('kpi-low').textContent = low;
document.getElementById('kpi-out').textContent = out;
}
Why derived state matters:
You have two choices:
A. Store quantity AND status.
Every time quantity changes, update status too.
Risk: forget one place, and the status is wrong.
You now have two sources of truth.
B. Store quantity. Derive status at render time.
Only one source of truth: quantity.
Status is always correct.
No possibility of drift.
B is the right choice. Every UI framework
that does "computed values" (React's useMemo,
Vue's computed, Svelte's $:, Solid's createMemo)
is formalizing exactly this idea.
In vanilla JS, the "computation" is just a
function called inside render(). Same result,
no framework needed.
Common derived values in this app:
→ stockStatus(product) (per-product)
→ stockLabel(product) (per-product, human text)
→ total inventory value (per-app)
→ product count (per-app)
→ low stock count (per-app)
→ out of stock count (per-app)
→ filtered products (per-app, from filter + query)
None of these are stored. All recomputed
from state.products on every render.
⚠️ When NOT to derive:
If a computation is expensive (e.g., parsing
a 10MB JSON), you might cache it. But even
then, cache the result with the source as the
key, not as a stored field on the product.
If a computation needs to survive a reload
for business reasons (e.g., "date marked as
low-stock"), store it separately as a distinct
fact. But for this app, nothing does.
The rule: store facts, derive display.
Fact: quantity is 8.
Fact: reorderLevel is 10.
Display: "Low stock" (derived from both facts).
If you store "Low stock" as a fact, you're
duplicating the logic. Two places can disagree.
✅ CRUD + duplicate SKU check
Same pattern as the CRM, with one new rule.
function addProduct(data) {
const now = new Date().toISOString();
state.products.unshift(Object.assign({
id: 'p_' + Date.now() + '_' + Math.random().toString(36).slice(2, 6),
createdAt: now,
updatedAt: now
}, data));
saveProducts();
render();
showToast('Product added.');
}
function updateProduct(id, data) {
const idx = state.products.findIndex(p => p.id === id);
if (idx === -1) return;
state.products[idx] = Object.assign({}, state.products[idx], data, {
updatedAt: new Date().toISOString()
});
saveProducts();
render();
showToast('Product updated.');
}
function deleteProduct(id) {
const p = state.products.find(x => x.id === id);
if (!p) return;
if (!confirm('Delete "' + p.name + '" (' + p.sku + ')?')) return;
state.products = state.products.filter(x => x.id !== id);
saveProducts();
render();
showToast('Product deleted.');
}
// ─── The new rule: duplicate SKU check ───
form.addEventListener('submit', function (e) {
e.preventDefault();
const data = {
sku: fieldSku.value.trim(),
name: fieldName.value.trim(),
category: fieldCategory.value.trim() || 'Uncategorized',
price: parseFloat(fieldPrice.value) || 0,
cost: parseFloat(fieldCost.value) || 0,
quantity: parseInt(fieldQuantity.value, 10) || 0,
reorderLevel: parseInt(fieldReorder.value, 10) || 0
};
if (!data.sku || !data.name) return;
// Reject duplicate SKU (unless editing the same product)
const duplicate = state.products.find(p =>
p.sku.toLowerCase() === data.sku.toLowerCase() &&
p.id !== fieldId.value
);
if (duplicate) {
showToast('SKU "' + data.sku + '" already exists.', true);
return;
}
if (fieldId.value) updateProduct(fieldId.value, data);
else addProduct(data);
closeModal();
});
The duplicate SKU check: Business rule: SKUs are unique. Two products with the same SKU is a data bug. Enforcement: reject the save, show a toast. ┌─────────────────────────────────────────┐ │ Find any product whose SKU matches │ │ (case-insensitive) AND whose id is │ │ not the one being edited. │ ├─────────────────────────────────────────┤ │ If found: show "SKU already exists" │ │ return without saving │ │ If not: proceed with add or update │ └─────────────────────────────────────────┘ Why case-insensitive: "SKU-001" and "sku-001" should be the same SKU for a warehouse scanner. Lowercase both sides, compare. Why exclude the current product: When editing an existing product, the SKU hasn't changed. The form re-submits the same SKU. Without the id check, saving would falsely flag a duplicate. Why check on submit, not on input: Checking on every keystroke would show "duplicate" mid-type for every keystroke. Check on submit — that's when the decision matters. If you wanted real-time feedback, you'd debounce the check (a callback to the debounce-throttle page). Where the check lives: In the form submit handler — the boundary where data enters the app. This is the right place: validate once, then trust. In Stage 03, the same rule goes on the server too (a UNIQUE constraint on the sku column). Client-side check is UX; server-side check is integrity. Both are needed. Never trust the client. The pattern across all CRUD: add → unshift → save → render → toast update → spread → save → render → toast delete → filter → save → render → toast Every path: state change → persistence → re-render → user feedback. Same three-step loop. Every time.
✅ Live KPI calculations
Total value, counts, low-stock.
function renderKPIs() {
let totalValue = 0;
let low = 0;
let out = 0;
state.products.forEach(function (p) {
// Inventory value = quantity × cost
// (what you paid for the stock on hand)
totalValue += p.quantity * p.cost;
const s = stockStatus(p);
if (s === 'low-stock') low++;
if (s === 'out-of-stock') out++;
});
document.getElementById('kpi-value').textContent = formatMoney(totalValue);
document.getElementById('kpi-count').textContent = formatNumber(state.products.length);
document.getElementById('kpi-low').textContent = formatNumber(low);
document.getElementById('kpi-out').textContent = formatNumber(out);
document.getElementById('kpi-value-delta').textContent = 'Quantity × cost';
document.getElementById('kpi-count-delta').textContent = 'Across all categories';
document.getElementById('kpi-low-delta').textContent = low === 0 ? 'None low' : 'Reorder soon';
document.getElementById('kpi-out-delta').textContent = out === 0 ? 'None out' : 'Reorder now';
}
function formatMoney(n) {
return '$' + Number(n).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
function formatNumber(n) {
return Number(n).toLocaleString();
}
Why quantity × cost, not quantity × price:
You have 100 units. Cost $5 each.
You sell them for $10 each.
What is the value of your inventory?
Cost basis: 100 × $5 = $500
Retail value: 100 × $10 = $1,000
The difference ($500) is unrealized
profit — you only earn it when you sell.
Until then, it's not an asset.
The standard accounting answer:
inventory value = cost × quantity.
If a manager wants to see "what could
this stock earn?", that's a separate
metric: quantity × (price - cost) =
potential profit. Or quantity × price =
retail value.
Stage 02 shows cost × quantity.
That's the real number that's sitting
on the shelf. Price is for sales
projections.
The KPI card deltas:
Value: "Quantity × cost" — explains the formula
Count: "Across all categories" — context
Low: "Reorder soon" — call to action
Out: "Reorder now" — urgent
Static deltas work here because
the numbers change on every render,
but the meaning doesn't. If you wanted
a delta vs. last week, you'd need
historical data (a Stage 04+ addition).
The formatMoney regex:
n.toFixed(2) → "1234.56"
.replace(regex, ...) → "1,234.56"
'$' + ... → "$1,234.56"
The regex \B(?=(\d{3})+(?!\d)) matches
positions where a comma should go —
between every 3 digits from the right.
Alternative: n.toLocaleString('en-US',
{ style: 'currency', currency: 'USD' })
→ "$1,234.56" (locale-aware, cleaner)
Both work. toLocaleString is preferable
for multi-locale apps. The regex is fine
for a demo.
The rule for KPI rendering:
Compute fresh on every render.
Never cache the computed value.
The cost of the computation is O(n)
with n = product count — trivially
fast for hundreds of products.
If you had 100,000 products, you'd
memoize the total (recompute only
when the product list changes).
Not needed for this app.
✅ The full file
The complete Stage 02 code, ready to run.
The complete file is at /apps/inventory/downloads/inventory-stage-02.html. It's the same file the earlier sections described, fully assembled. Open it in a browser to use it.
Right-click, save link as. Or open in a new tab and use File → Save Page.
Test it
Add a product, edit quantity, watch the stock badge change. Delete one. Search "SKU-002". Click "Low stock".
Break it (intentionally)
Try saving with SKU "SKU-001" twice — the second save shows a toast and is rejected.
Customize it
Add a "supplier" field to the model and form. Add it to the row rendering. Same pattern.
Extend it
Add a "Sort by: name / price / quantity" dropdown. State gets a sortBy, getFiltered sorts first. Same loop.
⚠️ Common mistakes
What to check if the app doesn't work.
render() after a changeThe UI doesn't update. Fix: every CRUD function ends with saveProducts(); render();.
status fieldIt goes stale when quantity changes. Fix: derive from quantity vs reorderLevel.
Overstates the value by unrealized profit. Fix: quantity × cost.
XSS hole. Fix: escapeHtml() on every string before innerHTML.
Two products can share an identifier. Fix: check on submit, exclude current id.
Handlers leak on every render. Fix: event delegation on tbody.
1000.5 shows as 1000.5, not $1,000.50. Fix: use formatMoney / formatNumber.
Crashes in private mode or when quota exceeds. Fix: wrap in try/catch.
❓ Frequently asked
What will I build in Stage 02?
A fully working inventory app. Add products (SKU, name, category, price, cost, quantity, reorder level), edit them, delete them, search by name or SKU, filter by category or low-stock status, and the KPI cards update in real time. Stock status is derived. All data persists to localStorage. One HTML file, no dependencies.
What does 'derived state' mean and why does it matter?
Derived state is a value computed from other state rather than stored separately. The stock status is derived from quantity and reorderLevel — not stored. This matters because stored state can go stale. Derived state can't go stale: it's always computed from the current data at render time.
Why reject duplicate SKUs?
Because a SKU is a unique business identifier. Two products with the same SKU would be a data error — ambiguous in the warehouse, on invoices, in reports. The form checks for duplicates before saving and shows a toast if found.
How do you calculate total inventory value?
Total value = sum(quantity × cost) for every product. Cost is what you paid to acquire the stock. Price is what you'd sell for, which only becomes revenue when it sells. Inventory value answers 'how much money is tied up in stock?' That's cost × quantity.
Why use localStorage again instead of a backend?
Because Stage 02 is about the frontend. localStorage is the simplest possible persistence. Stage 03 replaces it with Flask + SQLite. The UI barely changes — only where the data lives.
How do you make sure the KPI cards update correctly?
The render() function calls renderKPIs() at the end. renderKPIs() iterates over state.products, computes the values, then writes them into the KPI card DOM nodes. Because render() is called after every CRUD operation, the KPIs always reflect the current data.
🔗 Continue learning
Or explore related JavaScript concepts: