11import {
2- Middleware , MiddlewareAPI ,
2+ Middleware , SpecificMiddleware , MiddlewareAPI ,
33 applyMiddleware , createStore , Dispatch , Reducer , Action
44} from "../../index" ;
55
@@ -11,7 +11,15 @@ declare module "../../index" {
1111
1212type Thunk < S , O > = ( dispatch : Dispatch < S > , getState : ( ) => S ) => O ;
1313
14- const thunkMiddleware : Middleware =
14+ const thunkSpecificMiddleware : SpecificMiddleware < State > =
15+ ( { dispatch, getState} : MiddlewareAPI < State > ) =>
16+ ( next : Dispatch < State > ) =>
17+ < A extends Action , B > ( action : A | Thunk < State , B > ) : B | Action =>
18+ typeof action === 'function' ?
19+ ( < Thunk < State , B > > action ) ( dispatch , getState ) :
20+ next ( < A > action )
21+
22+ const thunkGenericMiddleware : Middleware =
1523 < S > ( { dispatch, getState} : MiddlewareAPI < S > ) =>
1624 ( next : Dispatch < S > ) =>
1725 < A extends Action , B > ( action : A | Thunk < S , B > ) : B | Action =>
@@ -20,7 +28,23 @@ const thunkMiddleware: Middleware =
2028 next ( < A > action )
2129
2230
23- const loggerMiddleware : Middleware =
31+ const loggerSpecificMiddleware : SpecificMiddleware < State > =
32+ ( { getState} : MiddlewareAPI < State > ) =>
33+ ( next : Dispatch < State > ) =>
34+ ( action : any ) : any => {
35+ console . log ( 'will dispatch' , action )
36+
37+ // Call the next dispatch method in the middleware chain.
38+ const returnValue = next ( action )
39+
40+ console . log ( 'state after dispatch' , getState ( ) )
41+
42+ // This will likely be the action itself, unless
43+ // a middleware further in chain changed it.
44+ return returnValue
45+ }
46+
47+ const loggerGenericMiddleware : Middleware =
2448 < S > ( { getState} : MiddlewareAPI < S > ) =>
2549 ( next : Dispatch < S > ) =>
2650 ( action : any ) : any => {
@@ -47,7 +71,7 @@ const reducer: Reducer<State> = (state: State, action: Action): State => {
4771
4872const storeWithThunkMiddleware = createStore (
4973 reducer ,
50- applyMiddleware ( thunkMiddleware )
74+ applyMiddleware ( thunkGenericMiddleware )
5175) ;
5276
5377storeWithThunkMiddleware . dispatch (
@@ -60,5 +84,5 @@ storeWithThunkMiddleware.dispatch(
6084
6185const storeWithMultipleMiddleware = createStore (
6286 reducer ,
63- applyMiddleware ( loggerMiddleware , thunkMiddleware )
87+ applyMiddleware ( loggerGenericMiddleware , thunkGenericMiddleware )
6488)
0 commit comments