|
13 | 13 | ![badge][badge-wasm] |
14 | 14 |
|
15 | 15 | A redux Thunk implementation for async action dispatch. |
16 | | -Thunk implement must implement the `Thunk` interface, which only has one dispatch method. |
17 | | -A more friendly way to create a thunk is with the `createThunk` function. Both are illustrated below: |
| 16 | +A Thunk must conform to the `Thunk` typealias, which is a function with 3 paramaters: `dispatch`, `getState`, & `extraArg`. |
| 17 | +A common use is to make a function return a `Thunk`. This allows passing params to the function. |
| 18 | + |
| 19 | +NOTE: Before v0.4.0 `Thunk` was an interface. Kotlin 1.3.70 fixed a bug which allows using a typealias instead, which is more concise and closer to the JS implementation. |
18 | 20 |
|
19 | 21 | ``` |
20 | 22 | val store = createStore(::reducer, applymiddleware(createThunkMiddleware())) |
21 | 23 | |
22 | 24 | ... |
23 | 25 | |
24 | | - class FooThunk: Thunk<State> { |
25 | | - |
26 | | - override fun dispatch(dispatch: Dispatcher, getState: GetState<State>, extraArg: Any?) { |
27 | | - dispatch(FetchingFooAction) |
28 | | - launch { |
29 | | - val result = api.foo() |
30 | | - if (result.isSuccessful()) { |
31 | | - dispatch(FetchFooSuccess(result.payload) |
32 | | - } else { |
33 | | - dispatch(FetchFooFailure(result.message) |
34 | | - } |
35 | | - } |
36 | | - } |
37 | | - } |
38 | | - |
39 | | - val fetchBar = createThunk<State> {dispatch, getState, extraArgument -> |
40 | | - dispatch(FetchingBarAction) |
| 26 | + fun fooThunk(query: String): Thunk<AppState> = { dispatch, getState, extraArg -> |
| 27 | + dispatch(FetchingFooAction) |
41 | 28 | launch { |
42 | | - val result = api.bar() |
| 29 | + val result = api.foo(query) |
43 | 30 | if (result.isSuccessful()) { |
44 | | - dispatch(FetchBarSuccess(result.payload) |
| 31 | + dispatch(FetchFooSuccess(result.payload) |
45 | 32 | } else { |
46 | | - dispatch(FetchBarFailure(result.message) |
47 | | - } |
48 | | - } |
49 | | - |
| 33 | + dispatch(FetchFooFailure(result.message) |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
50 | 38 | ... |
51 | 39 | |
52 | 40 | fun bar() { |
53 | | - dispatch(FooThunk()::dispatch) |
54 | | - dispatch(fetchBar) |
| 41 | + dispatch(fooThunk("my query")) |
55 | 42 | } |
56 | 43 | ``` |
57 | 44 |
|
|
0 commit comments