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.