Skip to main content
Frontend tutorial

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.

Work locally

You need Node.js 24, pnpm and Git (how to set them up). Clone this step’s starting code:

git clone --depth 1 \
--branch lesson-04-07-sum-start-v6 \
https://github.com/adam-zielonka/frontend-tutorial.git \
04-07-sum
cd 04-07-sum
pnpm install --frozen-lockfile
pnpm dev

To keep your own commits: git switch -c my-work.

Browse the source on GitHub (opens in a new tab)

Bring your browser edits

Choose Download my files in the ⋯ menu. It saves the lesson’s files as JSON. Stop the local server with Ctrl+C, copy the download into the project folder and run:

node import-draft.mjs ./04-07-sum-my-files.json
pnpm dev

The import replaces the project’s exercise files, so commit or back up local edits first.

Loading this step’s code…
Starting the live preview…