Mobxの主要はAPIについて調べた
computed
他のobservableから派生した値を自動的に計算し、キャッシュを提供する
状態に依存する派生値を効率的に計算する
import { computed, observable } from 'mobx'; const state = observable({ price: 100, quantity: 2, }); const total = computed(() => state.price * state.quantity); console.log(total.get()); // 200
action
状態を変更することを目的とした関数で使用
状態の変更を一箇所で管理し、副作用を追跡しやすくする
import { action, observable } from 'mobx'; const state = observable({ count: 0, }); const increment = action(() => { state.count++; }); increment(); // 状態の変更がアクション内で実行される
flow
非同期のアクションを扱うための仕組み
非同期処理を容易にし、リアクティブな状態管理を統一的に行う
import { flow, makeAutoObservable, flowResult } from "mobx" class Store { githubProjects = [] state = "pending" constructor() { makeAutoObservable(this, { fetchProjects: flow }) } // Note the star, this a generator function! *fetchProjects() { this.githubProjects = [] this.state = "pending" try { // Yield instead of await. const projects = yield fetchGithubProjectsSomehow() const filteredProjects = somePreprocessing(projects) this.state = "done" this.githubProjects = filteredProjects return projects } catch (error) { this.state = "error" } } } const store = new Store() const projects = await flowResult(store.fetchProjects())
runInAction
一時的にアクションのスコープを作成
アクション内で直接状態を変更する必要がある場合に使う
例えば、非同期関数のawait の後は状態管理対象外になっているため、アクションのラッピングが必要
import { runInAction, makeAutoObservable } from "mobx" class Store { githubProjects = [] state = "pending" // "pending", "done" or "error" constructor() { makeAutoObservable(this) } async fetchProjects() { this.githubProjects = [] this.state = "pending" try { const projects = await fetchGithubProjectsSomehow() const filteredProjects = somePreprocessing(projects) runInAction(() => { this.githubProjects = filteredProjects this.state = "done" }) } catch (e) { runInAction(() => { this.state = "error" }) } } }
toJS
observableオブジェクトを純粋なJavaScriptオブジェクトに変換
リアクティブ性を持たないオブジェクトが必要な場合に使用
import { observable, toJS } from 'mobx'; const state = observable({ count: 1, items: [1, 2, 3], }); const plainObject = toJS(state); console.log(plainObject); // { count: 1, items: [1, 2, 3] }