Search code examples
typescriptmobx

How to make two states in mobx that toggle each other?


I'm trying to create an object that has two flags that can't be both true. How do I do that? I can't find a relevant example in the docs. I was thinking somewhere in the lines of:

class Store {
  private _flag1: boolean = false;
  private _flag2: boolean = false;
  get flag1() { return this._flag1; }
  set flag1(v: boolean) { this._flag1 = v; if (v) this._flag2 = !v }
  get flag2() { return this._flag2; }
  set flag2(v: boolean) { this._flag2 = v; if (v) this._flag1 = !v }

  constructor() {
    makeObservable(this, { /* what do I write here??? */ }
  }
}

Solution

  • Mark underlying flags as observables, and getters as computeds, setters will be marked as actions automatically:

      constructor() {
        makeObservable(this, {
          _flag1: observable,
          _flag2: observable,
          flag1: computed,
          flag2: computed,
        }
      }
    

    Or you could you use makeAutoObservable to do this automatically.

    Relevant section from the docs