thunkMiddleware<State> function
- Store<
State> store, - dynamic action,
- NextDispatcher next
The thunkMiddleware intercepts and calls ThunkActions, which is simply a fancy name for any function that takes 1 argument: a Redux Store. This allows you to dispatch functions (aka ThunkActions) to your Store that can perform asynchronous work, then dispatch actions using the Store after the work is complete.
The dispatched ThunkActions will be swallowed, meaning they will not go
through the rest of your middleware to the Store
's Reducer
.
Example
// First, create a quick reducer final reducer = (String state, action) => action is String ? action : state;
// Next, apply the thunkMiddleware
to the Store
final store = new Store
// Create a ThunkAction
, which is any function that accepts the
// Store as it's only argument. Our function (aka ThunkAction) will
// simply send an action after 1 second. This is just an example,
// but in real life, you could make a call to an HTTP service or
// database instead!
final action = (Store
store.dispatch(searchResults);
};
Implementation
dynamic thunkMiddleware<State>(
Store<State> store,
dynamic action,
NextDispatcher next,
) {
if (action is ThunkAction<State>) {
return action(store);
} else if (action is CallableThunkAction<State>) {
return action.call(store);
} else {
return next(action);
}
}