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.