4.4. Global store + action for adding
We also know the users. One counter is not enough for them. To solve this, we create a new store that holds our CounterStores, and export it as store instead. Each counter also gets an id, so React can tell them apart in a list:
let nextId = 1;
export class CounterStore {
id = nextId++;
value = 0;
// ...
}
export class Store {
counters: CounterStore[] = [new CounterStore()];
constructor() {
makeAutoObservable(this);
}
addCounter = () => {
this.counters.push(new CounterStore());
};
}
export const store = new Store();
Now Counter gets its counter as a prop, and App renders all of them:
import { CounterStore, store } from './Store';
type Props = { counter: CounterStore };
const Counter = observer(({ counter }: Props) => {
const { value, add, reset } = counter;
// ...
});
function App() {
return <main className="app">
{store.counters.map(counter => (
<Counter key={counter.id} counter={counter} />
))}
<button onClick={store.addCounter}>+</button>
</main>;
}
export default observer(App);
App now reads state that can change, so it needs the second spell too. We can use it in the export line.
Need a hint?
- App reads store.counters, so App needs observer too.
Click + a few times. Every counter keeps its own value.