LoginSignup
10
5

More than 5 years have passed since last update.

20行で「すべて」理解するredux-thunk

Posted at

何かと議論の対象になるredux-thunkですが、本体はたった15行のライブラリです。

redux-thunk/src/index.js
function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

ミドルウェアのnextを隠匿して、「function型のactionが来たらそれを実行する」だけ。
素晴らしいコードは短いといういい例ですね。
今日のmeteor-fanの勉強会で教えてもらい衝撃だったのでメモ。
本家のreadmeが232行あって、コードの15倍くらいあるのが笑いどころでした。

10
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
10
5