Add interactions.
State → render → event.
In this stage, the CRM becomes a real app. You'll add JavaScript state, CRUD operations (create, read, update, delete), a search filter, status chips, and localStorage persistence. The whole thing is still one HTML file — no frameworks, no build tools. This is the state → render → event pattern that powers every UI framework. Learn it here, directly, and React and Vue stop being magic.
Short answer: One state object (customers + filter + query). One render() function that rebuilds the table and KPI cards from state. Event handlers that mutate state and call render(). localStorage.setItem on every change so data persists. escapeHtml() on every user string before innerHTML. Event delegation on the tbody for edit/delete. That's the whole app. No framework needed.
✅ What you'll build
The shell from Stage 01, now with working data.
Add
Click "Add customer", fill the modal form, hit Save. The customer appears at the top of the table immediately.
Edit
Click the ✎ icon on any row. The modal opens with the customer's data pre-filled. Save updates the row in place.
Delete
Click the × icon. Confirm the deletion, and the row disappears. The KPI counts update.
Search
Type in the search box. The table filters instantly by name, email, or company. Empty state shows if nothing matches.
Filter
Click All / Active / Leads / Inactive. Only matching customers show. Click another to switch.
Persist
Reload the page. Everything is still there. localStorage saved it.
✅ The state → render → event pattern
One loop, four functions.
// 1. STATE — one object, holds everything
const state = {
customers: [],
filter: 'all',
query: ''
};
// 2. RENDER — rebuilds DOM from state
function render() {
renderTable();
renderKPIs();
}
function renderTable() {
const rows = getFiltered(); // state → filtered list
if (rows.length === 0) {
tbody.innerHTML = '';
emptyState.style.display = 'block';
return;
}
emptyState.style.display = 'none';
tbody.innerHTML = rows.map(customerRowHTML).join('');
}
// 3. EVENTS — mutate state, call render
document.getElementById('search-input')
.addEventListener('input', function (e) {
state.query = e.target.value;
render();
});
document.querySelectorAll('[data-filter]')
.forEach(function (chip) {
chip.addEventListener('click', function () {
state.filter = chip.getAttribute('data-filter');
render();
});
});
// 4. CRUD — mutate state, save, render
function addCustomer(data) {
state.customers.unshift(newCustomer(data));
saveCustomers();
render();
}
function updateCustomer(id, data) {
const idx = state.customers.findIndex(c => c.id === id);
state.customers[idx] = { ...state.customers[idx], ...data };
saveCustomers();
render();
}
function deleteCustomer(id) {
state.customers = state.customers.filter(c => c.id !== id);
saveCustomers();
render();
}
Why this pattern works:
1. Single source of truth
The DOM reflects state. Never the
other way around. If the UI is wrong,
the state is wrong. Debug the state.
2. No DOM diffing needed
render() rebuilds the table from
scratch on every change. For a table
of 10-100 rows, this is fast enough
(a few milliseconds). When you have
thousands of rows, you'd switch to
a virtual DOM (or a framework that
does). But the mental model stays
the same: state → render.
3. Events are one line
Each event handler: mutate state,
call render. No imperative DOM
manipulation scattered through the
code. Every visual change goes
through render().
4. Debugging is easy
Log state at any point. Everything
the user sees is derived from it.
The same pattern in React:
const [customers, setCustomers] = useState([]);
const filtered = customers.filter(matches);
return <Table rows={filtered} />;
Events: setCustomers([...customers, new]);
React calls render() for you.
The same pattern in Vue:
const customers = ref([]);
const filtered = computed(...);
Events: customers.value.push(new);
Vue calls render() for you.
You are doing the same thing here,
with more lines and more clarity.
When you learn React later, you'll
recognize the pattern immediately.
"Ah — this is the state → render loop
I built in the CRM."
✅ CRUD operations
Create, Read, Update, Delete — in four functions.
// CREATE
function addCustomer(data) {
const now = new Date().toISOString();
const customer = {
id: 'c_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8),
name: data.name,
email: data.email,
phone: data.phone || '',
company: data.company || '',
status: data.status || 'lead',
notes: data.notes || '',
createdAt: now,
updatedAt: now
};
state.customers.unshift(customer); // newest first
saveCustomers();
render();
showToast('Customer added.');
}
// READ (filtered by search + status)
function getFiltered() {
const q = state.query.toLowerCase().trim();
return state.customers.filter(function (c) {
if (state.filter !== 'all' && c.status !== state.filter) return false;
if (!q) return true;
return (c.name + ' ' + c.email + ' ' + c.company)
.toLowerCase().indexOf(q) !== -1;
});
}
// UPDATE
function updateCustomer(id, data) {
const idx = state.customers.findIndex(c => c.id === id);
if (idx === -1) return false;
state.customers[idx] = {
...state.customers[idx],
...data,
updatedAt: new Date().toISOString()
};
saveCustomers();
render();
showToast('Customer updated.');
}
// DELETE
function deleteCustomer(id) {
const customer = state.customers.find(c => c.id === id);
if (!confirm('Delete "' + customer.name + '"?')) return;
state.customers = state.customers.filter(c => c.id !== id);
saveCustomers();
render();
showToast('Customer deleted.');
}
Each operation in three steps:
1. Mutate state
2. Save to localStorage
3. Call render()
That's it. The order matters
(save before render, so a failed
save doesn't show phantom data).
Why unshift (not push) for add:
New customers appear at the top
of the list. That's the UX for
most CRMs — newest first.
push would put them at the bottom,
where the user might not see them.
Why update via spread:
state.customers[idx] = {
...existing,
...newData,
updatedAt: new Date().toISOString()
}
Creates a NEW object, doesn't
mutate the old one. This is
the same pattern React uses for
state updates. It means nothing
else holding a reference to the
old object sees the change.
In vanilla JS this matters less
(nobody else holds the ref), but
it's the right habit. Learn it
here, use it in React later.
Why confirm before delete:
Deletion is destructive. A
single click should not lose
data. The confirm dialog is the
minimum protection.
In a real app, you might use an
undo toast instead ("Customer
deleted. Undo.") — but that's a
Stage 03+ feature. Confirm is
fine for Stage 02.
Why generate IDs with Date.now + random:
Date.now() is unique down to the
millisecond. Adding Math.random()
avoids collisions if two customers
are added in the same millisecond.
The underscore separates the parts.
Alternative: crypto.randomUUID()
(modern browsers). Cleaner but
requires a slightly newer browser.
The Date.now + random pattern works
everywhere.
✅ localStorage persistence
Two functions. Reload-safe.
const STORAGE_KEY = 'mak-crm-customers';
function loadCustomers() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) {
// First visit — seed with sample data
state.customers = SAMPLE_DATA.slice();
saveCustomers();
return;
}
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
state.customers = parsed;
} else {
state.customers = SAMPLE_DATA.slice();
}
} catch (e) {
// Corrupted data — fall back to samples
state.customers = SAMPLE_DATA.slice();
}
}
function saveCustomers() {
try {
localStorage.setItem(
STORAGE_KEY,
JSON.stringify(state.customers)
);
} catch (e) {
// Quota exceeded or localStorage disabled
showToast('Could not save. Storage may be full.');
}
}
// On page load
loadCustomers();
render();
localStorage limits:
Capacity: ~5MB per origin (varies by browser)
Type: strings only (JSON.stringify/parse)
Speed: synchronous (blocks the main thread)
Scope: per origin (https://makuistudio.com)
Persistence: until cleared by user or code
What it's good for:
✅ Small data (< 5MB)
✅ Client-side apps without a backend
✅ Drafts, preferences, caches
✅ Offline-first prototypes
What it's bad for:
❌ Large data (images, files, big datasets)
❌ Sensitive data (no encryption)
❌ Multi-user sync (it's per-device)
❌ Frequent writes (synchronous blocking)
Why synchronous is a problem:
Every setItem/getItem call blocks
the main thread for a few microseconds.
For a CRM with 5 customers, unnoticeable.
For a 1000-customer table saved on every
keystroke, it would jank.
Stage 03 replaces localStorage with
async fetch() calls to a server. The
save is non-blocking, and the data
scales beyond 5MB.
Error handling:
The try/catch around getItem and
setItem is not optional.
getItem can throw:
- In private browsing mode (Safari)
- When cookies are disabled
- When quota is exceeded
setItem can throw:
- When quota is exceeded (QuotaExceededError)
- When storage is disabled
If you don't catch these, the app
crashes for users in those conditions.
The try/catch means: "if storage is
broken, still let the app work."
The seed data pattern:
On first load, localStorage is empty.
Without seeding, the CRM shows nothing,
and the user has to add customers
before they can see anything working.
With seeding, the CRM is immediately
populated — the user sees a working
table, KPI counts, filtered views.
They can experiment before committing
real data.
Stage 03 seeds the SQLite database
the same way — a sample dataset
inserted on first migration.
✅ The full file
The complete Stage 02 code, ready to run.
The complete file is at /apps/crm/downloads/crm-stage-02.html. It's the same file the previous sections described, fully assembled. Open it in a browser to use it. Open it in a text editor to read it.
Right-click, save link as. Or open in a new tab and use File → Save Page.
Test it
Add a customer. Edit one. Delete one. Search. Filter. Reload. Everything should work and persist.
Break it (intentionally)
Open DevTools, clear localStorage, reload. The seed data comes back. Good — that's the fallback.
Customize it
Add a new field (e.g., "industry") to the model, form, and table row. The pattern is the same.
Extend it
Add a "sort" control (A-Z, newest, oldest). The pattern: state.sortBy, then sort in getFiltered.
⚠️ Common mistakes
What to check if the app doesn't work.
render() after a state changeThe UI doesn't update. Fix: every CRUD function ends with saveCustomers(); render();.
escapeHtml on user dataAn XSS hole. Fix: every string that goes into innerHTML must pass through escapeHtml().
Handlers leak on every render. Fix: event delegation on the tbody.
localStorage.setItem without try/catchCrashes in private mode or when quota exceeds. Fix: wrap in try/catch.
push instead of unshift for new customersNew customers appear at the bottom, where users miss them. Fix: unshift.
Not a bug in vanilla JS, but breaks the pattern. Fix: use spread or reassign.
Array.isArray after parseCorrupted storage returns an object, then crashes. Fix: check Array.isArray(parsed).
form.reset() when opening the modal for AddPrevious customer's data shows in the new form. Fix: form.reset() in openModal().
❓ Frequently asked
What will I build in Stage 02?
A fully working CRM. You can add customers, edit them, delete them, search by name/email/company, filter by status, and the KPI cards update in real time. All data persists to localStorage — reload the page and the customers are still there. The whole thing is one HTML file with inline JavaScript and CSS.
What is the state → render → event pattern?
It's the loop that powers every UI framework. (1) State is a plain object holding all data. (2) render() reads state and updates the DOM. (3) Events mutate state and call render() again. React, Vue, and Svelte do the same thing, with more abstraction. Learning it here makes every framework easier to understand.
Why use localStorage instead of a database?
Because Stage 02 is about the frontend. localStorage is the simplest possible persistence: synchronous key-value store in the browser, no server required. Stage 03 replaces it with a real SQLite database behind a Python Flask API. The UI doesn't change — only where the data lives.
Why is every customer rendered with escapeHtml?
Because user input can contain HTML. If a customer's name is <script>alert(1)</script>, rendering it without escaping would execute that script. escapeHtml converts dangerous characters to HTML entities, so they display as text. This is a cross-site scripting (XSS) defense.
Why is event delegation used for the edit/delete buttons?
Because the table is re-rendered on every state change. Attaching a click handler to each button would leak handlers on every render. Event delegation attaches one handler to the tbody, and uses event.target.closest('[data-action]') to find the button. One handler, no leaks.
What if I reload the page?
Your data persists. localStorage survives page reloads, browser restarts, and tab closures. If localStorage is empty (first visit), it seeds with the 5 sample customers. If corrupted, it falls back to the sample data.
🔗 Continue learning
Or explore related JavaScript concepts: