Stores are supposed to handle the events triggered by actions and emit the change to the listening view controllers.
Is it ok for them to trigger actions as well, for example in the callback of a request or directly in the store's registered callback.
For example:
AppDispatcher.register(function(payload) {
switch(payload.action.actionType) {
case Constants.PAGE_CHANGED:
ActionCreator.fetchNewData();
break;
case Constants.FETCH_DATA:
// save data
Store.emitChange();
break;
}
});
Is code like this "correct" in the Flux architecture ?
Thank you !
====== UPDATE BASED ON COMMENTS:
This is not a question of "I need to do this. How do I do it ?", but "Should this be a way of doing things". And I guess the answer is ... its your choice.
Some useful links were added in the comments, thanks for that.
My understanding of things is as follows:
In Flux architecture, the views should be the only ones triggering actions. Put the asynchronous requests in your action creator and the callback should launch a new action.
When not following the Flux steps, the store can also handle the asynchronous requests but make sure that the callback does not handle the data directly, but triggers another action instead. See Bill Fisher's answer regarding this.
In any case, as Ben Alpert's answer said, you can create multiple actions for a user action (eg: REQUEST_START, REQUEST_SUCCESS, REQUEST_ERROR), which allows you to hook into the different stages of your request.
Any updates on this are welcomed.
The short answer: Yes - triggering an action in the store is a bad practice.
And with the current version of the Dispatcher in react I don't even think that it's possible to dispatch a new action while dispatching, as you would when calling a new action in the store.
I properly a bit of a boy-scout when it comes to the flux pattern, but I have been pushing react projects to production where we decided to give it a full go and take the use of actions, stores, and events to the extreme regarding flux.
I think you should never makes the stores call new actions, as this can lead to a very weird behavior when the projects starts to evolve. It's right that it doesn't really "break" the data-flow thinking because you still (should) handle the response as normal and then it's all fine. But if you really have the need for this I would rather call what fetchNewData()
calls directly inside the first action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With