Skip to content

Commit

Permalink
Add comments to the thunk middleware implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed Oct 24, 2021
1 parent 56164ce commit 4937365
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,40 @@ export type {
ThunkMiddleware
} from './types'

// A function that accepts a potential "extra argument" value to be injected later,
// and returns an instance of the thunk middleware that uses that value
function createThunkMiddleware<
TState = {},
TBasicAction extends Action = AnyAction,
TExtraThunkArg = undefined
>(extraArgument?: TExtraThunkArg) {
// Standard Redux middleware definition pattern:
// See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
const middleware: ThunkMiddleware<TState, TBasicAction, TExtraThunkArg> =
({ dispatch, getState }) =>
next =>
action => {
// The thunk middleware looks for any functions that were passed to `store.dispatch`.
// If this "action" is really a function, call it and return the result.
if (typeof action === 'function') {
// Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
return action(dispatch, getState, extraArgument)
}

// Otherwise, pass the action down the middleware chain as usual
return next(action)
}
return middleware
}

// The standard thunk middleware has no extra argument included
const thunk = createThunkMiddleware()
// Attach the factory function so users can create a customized version
// with whatever "extra arg" they want to inject into their thunks
// @ts-ignore
thunk.withExtraArgument = createThunkMiddleware

// Convince TS that the default export has the right type for `withExtraArgument`
export default thunk as typeof thunk &
ThunkMiddleware & {
withExtraArgument<
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export interface ThunkDispatch<
*
* @template TReturnType The return type of the thunk's inner function
* @template TState The redux state
* @template TExtraThunkARg Optional extra argument passed to the inner function
* @template TExtraThunkArg Optional extra argument passed to the inner function
* (if specified when setting up the Thunk middleware)
* @template TBasicAction The (non-thunk) actions that can be dispatched.
*/
Expand Down

0 comments on commit 4937365

Please sign in to comment.