4.7. Sum of all counters
One more getter: the sum of all counters.
export class Store {
// ...
get sum(): number {
return this.counters.reduce((sum, c) => sum + c.value, 0);
}
}
It reads every counter's value, so MobX recalculates it when any counter changes, and when a counter is added or removed. We never store the sum anywhere; we derive it.
Show it above the counters, in a yellow card of its own:
function App() {
return <main className="app">
<div className="total">
<output>{store.sum}</output>
</div>
{store.counters.map(counter => (
Need a hint?
- reduce starts from 0, so an empty list sums to 0.
Change a few counters, then remove one. The sum follows.