Skip to main content
Frontend tutorial

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 ;.

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