Skip to content

Client State ​

state.js is an in-memory key-value store. It's the reason the "no diffing" design works at all.

Storage model ​

  • A single Map<string, string>; values are JSON.stringify'd strings.
  • Memory only: never touches sessionStorage / localStorage.
  • The real key is <object name>:<key>; keys prefixed with @ are global (@theme → theme).

How long it lives ​

  • Other tabs can't see it.
  • A reload always resets it. On purpose: this is not a draft-saving mechanism.

JS API ​

Only code inside the bundle (CGEvents) imports it. Templates should use declarative bindings.

js
import state from '../state.js';

const s = state.scope('customerPanel');

s.set('keyword', 'acme');
s.get('keyword', '');            // deep copy
s.merge('filters', { sort: 'id' });
s.update('tags', (t = []) => t.concat('vip'));
s.remove('keyword');
s.clear();                       // clears this namespace only

const off = s.subscribe('keyword', (value, key, previous) => { /* ... */ });
off();                           // hand-written subscriptions must be released
MethodNotifies subscribersNotes
get(key, fallback)—Returns a deep copy; mutating it doesn't affect the store
set(key, value)✅undefined means remove; returns false if not serializable
merge(key, patch)✅Shallow merge
update(key, fn)✅Writes back fn(current)
remove(key)✅Only notifies if a value existed
clear()✅ one by oneScoped version clears only its own keys
subscribe(key, fn)—'*' receives everything; returns off()

Value rules ​

CaseBehavior
Objects, arrays, strings, numbers, booleans, nullNormal
undefinedSame as delete
Functions, Map, Set, circular referencesWarns and does not write
DateComes back as an ISO string
s.get('o').x = 1Does not reach the store; use merge

No equality check

Writing the same value still notifies and re-renders. A subscriber that writes back to the same key loops forever.

What may go in ​

Yes: tabs, expand/collapse, filters, sort order, page numbers, scroll position, unsaved input, the current wizard step.

No: permissions, amounts, cart contents, anything the server must trust, passwords, File objects.

When to clear it yourself ​

WhenHow
After a successful savescope.clear(), otherwise old input overwrites the server's new values
Switching to a different recordscope.clear(), or use a different object name
LogoutNothing to do; full navigation clears it on pagehide

Linker can clear it too: ->then('state.clear', ['scope' => 'customerForm']).

Watching every change ​

js
document.addEventListener('cg:state', e => console.log('state', e.detail.key, '→', e.detail.value));