Skip to main content
Frontend tutorial

4.5. Limit number of counters

Sometimes we need to say to users: stop, you can't do this. You can only have four counters. So we add a getter that tells us whether the user can add more, and the action checks it too:

export class Store {
// ...
get canAddMoreCounters(): boolean {
return this.counters.length < 4;
}

addCounter = () => {
if (!this.canAddMoreCounters) return;
this.counters.push(new CounterStore());
};
}

A getter in a store is a computed value. MobX calculates it again only when counters changes, and when the result changes, every component that reads it renders again.

We can disable or hide the button when we're full of counters. Let's hide it:

{store.canAddMoreCounters && (
<button onClick={store.addCounter}>+</button>
)}
Need a hint?
  • A getter is read without parentheses: store.canAddMoreCounters.

Add counters until the + disappears.

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-05-limit-start-v6 \
https://github.com/adam-zielonka/frontend-tutorial.git \
04-05-limit
cd 04-05-limit
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-05-limit-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…