1
1
import {
2
- Middleware , MiddlewareAPI ,
2
+ Middleware , GenericMiddleware , MiddlewareAPI ,
3
3
applyMiddleware , createStore , Dispatch , Reducer , Action
4
4
} from "../../index" ;
5
5
@@ -11,7 +11,15 @@ declare module "../../index" {
11
11
12
12
type Thunk < S , O > = ( dispatch : Dispatch < S > , getState : ( ) => S ) => O ;
13
13
14
- const thunkMiddleware : Middleware =
14
+ const thunkSpecificMiddleware : Middleware < 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 : GenericMiddleware =
15
23
< S > ( { dispatch, getState} : MiddlewareAPI < S > ) =>
16
24
( next : Dispatch < S > ) =>
17
25
< A extends Action , B > ( action : A | Thunk < S , B > ) : B | Action =>
@@ -20,7 +28,23 @@ const thunkMiddleware: Middleware =
20
28
next ( < A > action )
21
29
22
30
23
- const loggerMiddleware : Middleware =
31
+ const loggerSpecificMiddleware : Middleware < 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 : GenericMiddleware =
24
48
< S > ( { getState} : MiddlewareAPI < S > ) =>
25
49
( next : Dispatch < S > ) =>
26
50
( action : any ) : any => {
@@ -47,7 +71,7 @@ const reducer: Reducer<State> = (state: State, action: Action): State => {
47
71
48
72
const storeWithThunkMiddleware = createStore (
49
73
reducer ,
50
- applyMiddleware ( thunkMiddleware )
74
+ applyMiddleware ( thunkGenericMiddleware )
51
75
) ;
52
76
53
77
storeWithThunkMiddleware . dispatch (
@@ -60,5 +84,5 @@ storeWithThunkMiddleware.dispatch(
60
84
61
85
const storeWithMultipleMiddleware = createStore (
62
86
reducer ,
63
- applyMiddleware ( loggerMiddleware , thunkMiddleware )
87
+ applyMiddleware ( loggerGenericMiddleware , thunkGenericMiddleware )
64
88
)
0 commit comments