4.9. Reaction (Bonus)
Let's store the counters in the URL params, so a link or a reload brings them back. First the store learns to turn its counters into text and back. A counter can now start with a value, so the constructor takes one:
export class CounterStore {
id = nextId++;
value = 0;
constructor(value = 0) {
this.value = value;
makeAutoObservable(this);
}
// ...
}
export class Store {
// ...
get asString(): string {
return this.counters.map(c => c.value).join(';');
}
fromString = (value: string) => {
this.counters = value.split(';').map(v =>
isNaN(+v) ? new CounterStore() : new CounterStore(+v));
};
}
Below export const store, read the URL once. Then a reaction writes it back: the first function says what to watch, and the second runs when that changes.
const urlParams = new URLSearchParams(window.location.search);
store.fromString(urlParams.get('value') || '');
reaction(() => store.asString, value => {
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('value', value);
window.history.replaceState({}, '', `?${urlParams}`);
});
Add reaction to the mobx import.
Need a hint?
- Add reaction to the mobx import.
- The URL code goes below export const store, so the store already exists.
Click a few buttons and add a counter, then watch the address bar above the preview. The counters are in the URL now; %3B is an encoded ;.