Redux Thunk

Thunk middleware for Redux.

build status npm version npm downloads

  1. npm install --save redux-thunk

Note on 2.x Update

Most tutorials today assume Redux Thunk 1.x so you might run into an issue when running their code with 2.x.
If you use Redux Thunk 2.x in CommonJS environment, don’t forget to add .default to your import:

  1. - var ReduxThunk = require('redux-thunk')
  2. + var ReduxThunk = require('redux-thunk').default

If you used ES modules, you’re already all good:

  1. import ReduxThunk from 'redux-thunk' // no changes here 😀

Additionally, since 2.x, we also support a UMD build:

  1. var ReduxThunk = window.ReduxThunk.default

As you can see, it also requires .default at the end.

Why Do I Need This?

If you’re not sure whether you need it, you probably don’t.

Read this for an in-depth introduction to thunks in Redux.

Motivation

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.

An action creator that returns a function to perform asynchronous dispatch:

  1. const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
  2. function increment() {
  3. return {
  4. type: INCREMENT_COUNTER
  5. };
  6. }
  7. function incrementAsync() {
  8. return dispatch => {
  9. setTimeout(() => {
  10. // Yay! Can invoke sync or async actions with `dispatch`
  11. dispatch(increment());
  12. }, 1000);
  13. };
  14. }

An action creator that returns a function to perform conditional dispatch:

  1. function incrementIfOdd() {
  2. return (dispatch, getState) => {
  3. const { counter } = getState();
  4. if (counter % 2 === 0) {
  5. return;
  6. }
  7. dispatch(increment());
  8. };
  9. }

What’s a thunk?!

A thunk is a function that wraps an expression to delay its evaluation.

  1. // calculation of 1 + 2 is immediate
  2. // x === 3
  3. let x = 1 + 2;
  4. // calculation of 1 + 2 is delayed
  5. // foo can be called later to perform the calculation
  6. // foo is a thunk!
  7. let foo = () => 1 + 2;

The term originated as a humorous past-tense version of “think”.

Installation

  1. npm install --save redux-thunk

Then, to enable Redux Thunk, use applyMiddleware():

  1. import { createStore, applyMiddleware } from 'redux';
  2. import thunk from 'redux-thunk';
  3. import rootReducer from './reducers/index';
  4. // Note: this API requires redux@>=3.1.0
  5. const store = createStore(
  6. rootReducer,
  7. applyMiddleware(thunk)
  8. );

Composition

Any return value from the inner function will be available as the return value of dispatch itself. This is convenient for orchestrating an asynchronous control flow with thunk action creators dispatching each other and returning Promises to wait for each other’s completion:

  1. import { createStore, applyMiddleware } from 'redux';
  2. import thunk from 'redux-thunk';
  3. import rootReducer from './reducers';
  4. // Note: this API requires redux@>=3.1.0
  5. const store = createStore(
  6. rootReducer,
  7. applyMiddleware(thunk)
  8. );
  9. function fetchSecretSauce() {
  10. return fetch('https://www.google.com/search?q=secret+sauce');
  11. }
  12. // These are the normal action creators you have seen so far.
  13. // The actions they return can be dispatched without any middleware.
  14. // However, they only express “facts” and not the “async flow”.
  15. function makeASandwich(forPerson, secretSauce) {
  16. return {
  17. type: 'MAKE_SANDWICH',
  18. forPerson,
  19. secretSauce
  20. };
  21. }
  22. function apologize(fromPerson, toPerson, error) {
  23. return {
  24. type: 'APOLOGIZE',
  25. fromPerson,
  26. toPerson,
  27. error
  28. };
  29. }
  30. function withdrawMoney(amount) {
  31. return {
  32. type: 'WITHDRAW',
  33. amount
  34. };
  35. }
  36. // Even without middleware, you can dispatch an action:
  37. store.dispatch(withdrawMoney(100));
  38. // But what do you do when you need to start an asynchronous action,
  39. // such as an API call, or a router transition?
  40. // Meet thunks.
  41. // A thunk is a function that returns a function.
  42. // This is a thunk.
  43. function makeASandwichWithSecretSauce(forPerson) {
  44. // Invert control!
  45. // Return a function that accepts `dispatch` so we can dispatch later.
  46. // Thunk middleware knows how to turn thunk async actions into actions.
  47. return function (dispatch) {
  48. return fetchSecretSauce().then(
  49. sauce => dispatch(makeASandwich(forPerson, sauce)),
  50. error => dispatch(apologize('The Sandwich Shop', forPerson, error))
  51. );
  52. };
  53. }
  54. // Thunk middleware lets me dispatch thunk async actions
  55. // as if they were actions!
  56. store.dispatch(
  57. makeASandwichWithSecretSauce('Me')
  58. );
  59. // It even takes care to return the thunk’s return value
  60. // from the dispatch, so I can chain Promises as long as I return them.
  61. store.dispatch(
  62. makeASandwichWithSecretSauce('My wife')
  63. ).then(() => {
  64. console.log('Done!');
  65. });
  66. // In fact I can write action creators that dispatch
  67. // actions and async actions from other action creators,
  68. // and I can build my control flow with Promises.
  69. function makeSandwichesForEverybody() {
  70. return function (dispatch, getState) {
  71. if (!getState().sandwiches.isShopOpen) {
  72. // You don’t have to return Promises, but it’s a handy convention
  73. // so the caller can always call .then() on async dispatch result.
  74. return Promise.resolve();
  75. }
  76. // We can dispatch both plain object actions and other thunks,
  77. // which lets us compose the asynchronous actions in a single flow.
  78. return dispatch(
  79. makeASandwichWithSecretSauce('My Grandma')
  80. ).then(() =>
  81. Promise.all([
  82. dispatch(makeASandwichWithSecretSauce('Me')),
  83. dispatch(makeASandwichWithSecretSauce('My wife'))
  84. ])
  85. ).then(() =>
  86. dispatch(makeASandwichWithSecretSauce('Our kids'))
  87. ).then(() =>
  88. dispatch(getState().myMoney > 42 ?
  89. withdrawMoney(42) :
  90. apologize('Me', 'The Sandwich Shop')
  91. )
  92. );
  93. };
  94. }
  95. // This is very useful for server side rendering, because I can wait
  96. // until data is available, then synchronously render the app.
  97. store.dispatch(
  98. makeSandwichesForEverybody()
  99. ).then(() =>
  100. response.send(ReactDOMServer.renderToString(<MyApp store={store} />))
  101. );
  102. // I can also dispatch a thunk async action from a component
  103. // any time its props change to load the missing data.
  104. import { connect } from 'react-redux';
  105. import { Component } from 'react';
  106. class SandwichShop extends Component {
  107. componentDidMount() {
  108. this.props.dispatch(
  109. makeASandwichWithSecretSauce(this.props.forPerson)
  110. );
  111. }
  112. componentDidUpdate(prevProps) {
  113. if (prevProps.forPerson !== this.props.forPerson) {
  114. this.props.dispatch(
  115. makeASandwichWithSecretSauce(this.props.forPerson)
  116. );
  117. }
  118. }
  119. render() {
  120. return <p>{this.props.sandwiches.join('mustard')}</p>
  121. }
  122. }
  123. export default connect(
  124. state => ({
  125. sandwiches: state.sandwiches
  126. })
  127. )(SandwichShop);

Injecting a Custom Argument

Since 2.1.0, Redux Thunk supports injecting a custom argument using the withExtraArgument function:

  1. const store = createStore(
  2. reducer,
  3. applyMiddleware(thunk.withExtraArgument(api))
  4. )
  5. // later
  6. function fetchUser(id) {
  7. return (dispatch, getState, api) => {
  8. // you can use api here
  9. }
  10. }

To pass multiple things, just wrap them in a single object and use destructuring:

  1. const store = createStore(
  2. reducer,
  3. applyMiddleware(thunk.withExtraArgument({ api, whatever }))
  4. )
  5. // later
  6. function fetchUser(id) {
  7. return (dispatch, getState, { api, whatever }) => {
  8. // you can use api and something else here
  9. }
  10. }

License

MIT