0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

redux thunkの内部実装について

Last updated at Posted at 2018-11-10

今までなんとなく使っていたredux thunkだったが、内部実装を理解して簡単にまとめた。

サンプルコード

action/index.js
export const toggleTodoAction = id => dispatch => {
  setTimeout(() => {
    dispatch({type: TYPE.TOGGLE_TODO, payload: {id}})
  }, 1000)
}
export const changeFilterTypeAction = filterType => ({type: TYPE.CHANGE_FILTER_TYPE, payload: {filterType}})
export const addTodoAction = name => ({type: TYPE.ADD_TODO, payload: {name}})

コンポーネント側でイベントが起きた時に、toggleTodoActionは関数を返し、changeFilterTypeActionとaddTodoActionはオブジェクトを返すことになる。

store.js
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './reducers'

const thunk = store => next => action => {
  typeof action === 'function' ? action(store.dispatch) : next(action)
}

export default createStore(rootReducer, applyMiddleware(thunk))

thunkでは対象のアクションが関数なのかそうではないかで次の動きが決まる。
toggleTodoActionは関数を返すのでstore.dispatchをラップすることによってaction内で非同期処理などを書くことができる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?