4.2. Create store + first spell
So let's build a store outside React, where everything can reach it. A store is a class: fields hold the state, and actions change it. Write it in /Store.ts:
import { makeAutoObservable } from 'mobx';
export class CounterStore {
value = 0;
constructor() {
makeAutoObservable(this);
}
add = (value: number) => {
this.value += value;
console.log(this.value);
};
reset = () => {
this.value = 0;
};
}
export const store = new CounterStore();
To tell MobX that this class is a store, we use the first spell, makeAutoObservable, in the constructor. After that the object isn't a normal object anymore: fields become state, methods become actions and getters become computed values. We write actions as arrow functions, so they keep this wherever we pass them.
Now Counter can use the store instead of useState:
import { store } from './Store';
import './styles.css';
function Counter() {
const { value, add, reset } = store;
return <div className="counter">
<output>{value}</output>
<button onClick={() => add(-100)}>-100</button>
<button onClick={() => add(-1)}>-1</button>
<button onClick={() => reset()}>0</button>
<button onClick={() => add(1)}>+1</button>
<button onClick={() => add(100)}>+100</button>
</div>;
}
Need a hint?
- Write actions as arrow functions, so add and reset keep their this after destructuring.
Click +1 a few times: nothing changes. Then open Console under the preview: the value went up. MobX changed it, but React doesn't know that it should render again.