Mobx core - ChoDragon9/posts GitHub Wiki

Creating observable state

decorator

import {action, computed, observable} from 'mobx';

class Doubler {
  @observable value;

  constructor(value) {
    this.value = value
  }

  @computed get double() {
    return this.value * 2
  }

  @action increment() {
    this.value++
  }
}

class + makeObservable

import {action, computed, makeObservable, observable} from 'mobx';

class Doubler {
  value;

  constructor(value) {
    makeObservable(this, {
      value: observable,
      double: computed,
      increment: action
    });
    this.value = value
  }

  get double() {
    return this.value * 2
  }

  increment() {
    this.value++
  }
}

factory function + makeAutoObservable

import {makeAutoObservable} from 'mobx';

function createDoubler (value) {
  return makeAutoObservable({
    value,
    get double() {
      return this.value * 2
    },
    increment() {
      this.value++
    }
  })
}

observable

import {action, observable} from 'mobx';

const state = observable({
  value: 0,
  get double() {
    return this.value * 2
  }
});
const increment = action(state => {
  state.value++
});