mobx
getter does not seem to react to changes in localStorage.
class Test {
constructor() {
makeAutoObservable(this);
this.setCount = this.setCount.bind(this);
}
private static _instance: Test;
static get instance(): Test {
if (!this._instance) {
this._instance = new Test();
}
return this._instance;
}
get count(): number | null {
const value: string | null = localStorage.getItem("count");
if (!value) {
return null;
}
return JSON.parse(value);
}
// was 0, updating to 1
setCount(newValue: number): void {
localStorage.setItem("count", JSON.stringify(value));
console.log(
"updated count",
newValue, // 1
"getter local storage?",
this.count, // 0, old value !!!!
"direct access local storage?",
JSON.parse(localStorage.getItem("count") ?? "null"), // 1, new value
);
}
}
direct access local storage
after the update logs the new value, but getter local storage
, which runs the same code behind a mobx
computed, does not update unless a hard refresh occurs.
I have all functions in this class observable in the constructor, and the class is initialized once at the app root (logged initialization to be sure). All references use Test.instance
, so it’s not reinitializing the class.
Local storage is not async in any way, so it shouldn’t lag in its update.
I’m perplexed.
I know I can just set the value as an observable and not use a computed getter to resolve this, but I’d like to know the fundamental reason behind this.