index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132
  1. /** A function that accepts a potential "extra argument" value to be injected later,
  2. * and returns an instance of the thunk middleware that uses that value
  3. */
  4. function createThunkMiddleware(extraArgument) {
  5. // Standard Redux middleware definition pattern:
  6. // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
  7. var middleware = function middleware(_ref) {
  8. var dispatch = _ref.dispatch,
  9. getState = _ref.getState;
  10. return function (next) {
  11. return function (action) {
  12. // The thunk middleware looks for any functions that were passed to `store.dispatch`.
  13. // If this "action" is really a function, call it and return the result.
  14. if (typeof action === 'function') {
  15. // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
  16. return action(dispatch, getState, extraArgument);
  17. } // Otherwise, pass the action down the middleware chain as usual
  18. return next(action);
  19. };
  20. };
  21. };
  22. return middleware;
  23. }
  24. var thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version
  25. // with whatever "extra arg" they want to inject into their thunks
  26. thunk.withExtraArgument = createThunkMiddleware;
  27. export default thunk;