LoginSignup
11
5

More than 5 years have passed since last update.

redux-thunk や redux-saga がつらかった

Last updated at Posted at 2017-12-17

ので redux-capsule を作りました

これは何?

以下の動機で作られた redux middleware です

  • 関数ベースではなくクラスベースで dispatcher を設計したい
    • redux-thunk(dispatch, getState) を引き回すのがつらい
    • そもそも関連のある処理は同じクラスにまとめたい
  • 非同期処理のためだけに新しい仕組みを導入したくない
    • redux-saga って本当に必要なんだろうか(反語)

サンプルコード

dispatchgetState をクラスの中で扱えるようになります

import { ReduxCapsule } from 'redux-capsule';
import { increase } from './actions';

export class CounterButton extends ReduxCapsule {
  onClick = () => {
    this.dispatch(increase(1));
  };
  get label() {
    return `increment counter : ${this._currentCount}`;
  }
  get _currentCount() {
    // this.state は this.getState() と等価
    return this.state.sampleCounter.count;
  }
}

react-redux による利用例はこんな感じです

import React from 'react';
import { connect } from 'react-redux';
import { CounterButton } from './CounterButton';

const SampleView = props => {
  const button = props.createCounterButton();
  return (
    <div>
      <button type='button' onClick={button.onClick}>
        {button.label}
      </button>
    </div>
  );
};
const mapStateToProps = state => state;

const mapDispatchToProps = {
  createCounterButton: () => CounterButton,
};
export default connect(mapStateToProps, mapDispatchToProps)(SampleView);

その他テストや非同期処理などの実装方法については通常のクラスと同様なので省略します

導入方法

npm install --save redux-capsule

あとはいつもどおりに applyMiddleware を呼びましょう

import { createStore, applyMiddleware } from 'redux';
import { capsule } from 'redux-thunk';

const store = createStore(
  _ => _,// rootReducer
  applyMiddleware(capsule)
);

関連リンク

  • ReduxでのMiddleware不要論
    • 動機は異なるものの発想はほぼ同じです
    • ただ、毎回 dispatch => ... new ...(dispatch, someClient)
      書くのも嫌だったので、結局今回のような middleware を作ることにしました
11
5
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
11
5