Skip to main content
Frontend tutorial

4.10. Autorun (Bonus)

Let's also store the counters in localStorage, for the times you open the app without the link. When the URL has no value, the saved one is the fallback:

const urlParams = new URLSearchParams(window.location.search);
const saved = localStorage.getItem('counters');
store.fromString(urlParams.get('value') || saved || '');

To save the counters, we use autorun. It runs once right away, and again whenever something it read changes. Unlike reaction, it has no separate function that says what to watch: it tracks everything it reads.

autorun(() => {
localStorage.setItem('counters', store.asString);
});

Add it after the reaction, and add autorun to the mobx import.

Need a hint?
  • Add autorun to the mobx import.
  • The URL comes first in the || chain, so a shared link still wins.

Do it in your own code (the solution view doesn't survive a reload): change a few counters, then reload this page. The address bar starts empty, but your counters come back.

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