While starting to build an app using flutter and redux I came across the following issue: What's the best way to handle a network request or any asynchronous action?
The context: Make an asynchronous call to get a string from the server side (In my case just a Future.delayed) when the request finishes update the state and see the change in the view.
First Approach:
Create a middlewareClass that has an async call function that will wait for the asynchronous event to finish after it finishes call NextDispacther with a new action that will be treated in the reducers
class UserTypeMiddleware extends MiddlewareClass<AppState> {
@override
void call(Store<AppState> store, action, NextDispatcher next) async{
if (action is GetTitleAction) {
String title = await Future<String>.delayed(Duration(seconds: 2), () {
return "This is a title ";
});
next(UpdateTitleAction(title));
} else {
next(action);
}
}
}
Second approach:
Create a typedMiddleware that does kind of the same thing but it dispatches the action via store.dispatch
TypedMiddleware<AppState, GetTitleAction> userTypeMiddleware() =>
TypedMiddleware<AppState, GetTitleAction>(_getTitle);
Future _getTitle(Store<AppState> store, GetTitleAction action, NextDispatcher next) async {
String title = await Future<String>.delayed(Duration(seconds: 2), () {
return "Flow.me este o aplicatie care va permite sa inchiriati un scooter ";
});
store.dispatch(UpdateTitleAction(title));
next(action);
}
Third approach:
Use redux_thunk
ThunkAction<AppState> updateTitleAction = (Store<AppState> store) async {
String title = await Future<String>.delayed(Duration(seconds: 2), () {
return "Flow.me este o aplicatie care va permite sa inchiriati un scooter ";
});
store.dispatch(UpdateTitleAction(title));
};
From my point of view I would rather deal with the logic of handling server request in the middleware and not in an action - just for the sake of consistency - middlewares being at the same level as a reducer, for handling logic.
Does it break the redux idea in any way if I am calling NextDispatcher in the middleware with a delay from the async request? Could this represent a problem?