Repository navigation
Persist computed value to disk via reaction? #4627
Replies: 2 comments 1 reply
|
@bforte Since you want to persist after a value changes, Pattern: class Store {
@observable _cache = {}
constructor() {
this.hydrate();
// Setup persistence listener
reaction(
() => JSON.stringify(this._cache),
(json) => localStorage.setItem(''key'', json)
);
}
}Keeping the "minting" logic separate from the "persistence" logic is cleaner. |
|
Building on @aniruddhaadak80's point, I'd go one step further on why this specific shape is fragile. The core issue is that It mostly works because unobserved computeds recompute on every access rather than being cached, per MobX's docs: "If you access I'd separate the persistence concern entirely instead of routing it through the computed: class SeedStore {
_cache = {}
constructor() {
makeAutoObservable(this)
reaction(
() => JSON.stringify(this._cache),
(json) => persistToStorage(json),
)
}
getOrMintSeed(key: string) {
return (this._cache[key] ??= Math.random())
}
}Keep |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Have a peculiar case of wanting to use a reaction to automatically persist, in storage, values that are generated during a computed derivation.
Below is improper mobx but hopefully illustrative.
It seems like it might be best to mint seeds in a
SeedConsumerconstructor, but it's problematic or impossible -- Many concreteSeedConsumerclasses won't touchseededRandomat all; those that would use it may be destroyed before accessing it; those that do access it may want to include, in the param/key, app/instance state unique to the time at which seededRandom is first accessed, so ideally the SeedStore generates and caches a value only when absolutely needed.All reactions