LoginSignup
2
1

More than 5 years have passed since last update.

unstated-debugを使ってunstatedのデバッグをする

Posted at

sindresorhus/unstated-debug: Debug your Unstated containers with ease

// @flow
import * as React from 'react'
import { Provider, Subscribe, Container } from 'unstated'
import UNSTATED from 'unstated-debug' // eslint-disable-line no-unused-vars

type CounterState = {
  count: number
}

class CounterContainer extends Container<CounterState> {
  state = { count: 0 }
  increment() {
    this.setState({ count: this.state.count + 1 })
  }
  decrement() {
    this.setState({ count: this.state.count - 1 })
  }
}

function Counter() {
  return (
    <Subscribe to={[CounterContainer]}>
      {counter => (
        <div>
          <button onClick={() => counter.decrement()}>-</button>
          <span>{counter.state.count}</span>
          <button onClick={() => counter.increment()}>+</button>
        </div>
      )}
    </Subscribe>
  )
}

function App() {
  return (
    <Provider>
      <Counter />
    </Provider>
  )
}

export default App

unstated-debugをインポートするだけで機能するが、暗黙的な処理をするので、eslint-disable-line no-unused-varsとかきっと書くはめになる。もちろんdevのみ有効にした方がいいでしょう。

これを使うと、redux-loggerのように状態の追跡ができる。個人的には常に有効化するとうるさいので必要なときに有効化するといいと思う。以下の任意の場所に挟めばデフォルトでログを表示しなくなる。あとはfalseの部分をprocess.env.DEBUG的なのに置き換えてwebpackで制御するのもありだと思う。

UNSTATED.logStateChanges = false;

Chromeのconsoleタブを開いてUNSTATEDと打てば、現在の状態やログが取れるので、stateの確認に便利。

jamiebuilds/unstated: State so simple, it goes without saying
sindresorhus/unstated-debug: Debug your Unstated containers with ease

2
1
0

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
2
1