Derive view models from canonical application state
Quick answer
A selector computes values needed by a view from canonical application data. Store the underlying facts and derive counts, totals and filtered rows rather than maintaining independent mutable copies of the same information.
How it works
Use a pure function whose arguments are state and selection criteria. For a small list, recomputing is often simpler than caching. If memoizing by reference, require immutable inputs; in-place mutations may leave an identity-based cache stale. A view model can format values and expose flags, while domain data stays independent of the UI. This extends earlier derived-control state into application-level selectors.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const state={items:[{id:"A",qty:2},{id:"B",qty:0},{id:"C",qty:4}]};const select=s=>({visible:s.items.filter(x=>x.qty>0).map(x=>x.id),total:s.items.reduce((n,x)=>n+x.qty,0)});console.log(JSON.stringify(select(state)));})()Expected console output:
{"visible":["A","C"],"total":6}Both visible IDs and the total are computed from the same source facts.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const rows=[1,2];const cached={input:rows,total:3};rows.push(4);console.log(cached.input===rows,cached.total,rows.reduce((a,b)=>a+b,0));})()Expected console output:
true 3 7The in-place change preserves identity but invalidates the saved total.
Common mistakes
Do not separately increment a stored count if it can be derived from the canonical array. Do not memoize solely by reference while mutating the referenced data.
Practice
Compute visible item IDs and total stock from state and a search criterion. Verify that selectors do not mutate the state.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Derive view models from canonical application state — Knowledge Check
Apply the concept and reason about local example output.
What should normally be the canonical source for a count of visible records?
When can identity-based memoization return stale values?
What does a view-model selector help isolate?
What is the exact console output in Derive view models from canonical application state example 1?
(async () => {const state={items:[{id:"A",qty:2},{id:"B",qty:0},{id:"C",qty:4}]};const select=s=>({visible:s.items.filter(x=>x.qty>0).map(x=>x.id),total:s.items.reduce((n,x)=>n+x.qty,0)});console.log(JSON.stringify(select(state)));})()What is the exact console output in Derive view models from canonical application state example 2?
(async () => {const rows=[1,2];const cached={input:rows,total:3};rows.push(4);console.log(cached.input===rows,cached.total,rows.reduce((a,b)=>a+b,0));})()