LoginSignup
3
1

More than 5 years have passed since last update.

MobX 4 から flow という紛らわしい名前の API が加わりました

Last updated at Posted at 2018-06-06

MobX 3 系では、今まで非同期処理を書くのが若干冗長でした。

こう書いていたのが

import { observable, runInAction } from 'mobx'
import { someApi } from '../api'

class SomeStore {
    @observable someState = ''

    async someAction() {
        const res = await someApi.fetch()
        runInAction(() => {
            this.someState = res.data
        })
    }
}

MobX 4 からは、 flow という紛らわしい名前の API を使ってこう書けます。

import { observable, flow } from 'mobx'
import { someApi } from '../api'

class SomeStore {
    @observable someState = ''

    someAction = flow(function * () {
        this.someState = yield someApi.fetch()
    })
}

中身でどうやっているか分からないですが、すっきりしました。
ジェネレーターとクラスプロパティを使っててかっこいいです。

ただ、エラー処理まで入れると、従来のPromiseの方がシンプルな気もします。

import { observable, action } from 'mobx'
import { someApi } from '../api'

class SomeStore {
    @observable someState = ''
    @observable error = null

    someAction() {
        someApi.fetch().then(
            action(res => this.someState = res.data),
            action(err => this.err = err),
        )
    }
}
3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1