marcglasberg / async_redux

Flutter Package: A Redux version tailored for Flutter, which is easy to learn, to use, to test, and has no boilerplate. Allows for both sync and async reducers.
Other
234 stars 40 forks source link

Dispatch Action from reduce fonction #42

Closed raphFlash closed 4 years ago

raphFlash commented 4 years ago

Hello,

I'm trying AsyncRedux and i found it really great. Nevertheless I have a question about the Action.

If I dispatch an action2 from the reduce fonction of action1, the action2 is executed before the store gets updated from the action1. If the action2 needs that updated data, it's a problem.

So I tried to dispatch the action2 in the after method of the action1. It works but if a have an error in the action1, I don't want the action2 dispatched but the after method is called anyway.

Do you have a solution ? Thanks you.

marcglasberg commented 4 years ago

The after method is always called. It's like a finally block.

If I understand your question, you want to dispatch Action1, and only then dispatch Action2, but only if Action1 succeeded. Why don't you create some Action3 to dispatch both of them?

class Action3 ...

AppState reduce() {
   dispatch(Action1());
   dispatch(Action2());
}

I am assuming Action1 is sync. If Action1 is async you have to use await dispatchFuture(Action1());

Does that solve your problem?

raphFlash commented 4 years ago

Thanks for the answer. It works !

But I think it's a very basic use case to dispatch an action at the end of another action. And you almost always want the store to be updated before launching the other action. So adding each time another action to do that feels very verbose.

It would be nice to have a method like after() but only trigger when no errors occurred.

marcglasberg commented 4 years ago

It is a basic use case, yes. But suppose you have three actions in a row you want to dispatch. That's also a basic use case. Then you'd need two methods like after. And then it starts to get complex. Some small verbosity sometimes is necessary to achieve simplicity. Thanks!

raphFlash commented 4 years ago

Ok, thank you for your explanation.

I ended up having a BaseAction class like this

abstract class BaseAction extends ReduxAction<AppState> {
  bool hasError = false;

  @override
  Object wrapError(error) {
    hasError = true;
    return super.wrapError(error);
  }
} 

and checking the value of hasError in the after() method.

And thanks again fro this great lib.

marcglasberg commented 4 years ago

Interesting solution to what you want to do. Congrats.