Is it a good practice to call action within another action (in flux) - flux

I have an action as follows:
SomeActions.doAction1(){
//..dispatch event "started"...
//...do some process....
FewActions.doAnotherAction(); //CAN WE DO THIS
//...do something more....
//..dispatch event "completed"..
}
While the above works with no problems, just wondering, if it is valid according to flux pattern/standard or is there a better way.
Also, I guess calling Actions from Stores are a bad idea. Correct me if I am wrong.

Yes, calling an Action within another Action is a bad practice. Actions should be atomic; all changes in the Stores should be in response to a single action. They should describe one thing that happened in the real world: the user clicked on a button, the server responded with data, the screen refreshed, etc.
Most people get confused by Actions when they are thinking about them as imperative instructions (first do A, then do B) instead of descriptions of what happened and the starting point for reactive processes.
This is why I recommend to people that they name their Action types in the past tense: BUTTON_CLICKED. This reminds the programmer of the fundamentally externally-driven, descriptive nature of Actions.
Actions are like a newspaper that gets delivered to all the stores, describing what happened.
Calling Actions from Stores is almost always the wrong thing to do. I can only think of one exception: when the Store responds to the first Action by starting up an asynchronous process. When the async process completes, you want to fire off a second Action. This is the case with a XHR call to the server. But the better way is to put the XHR handling code into a Utils module. The store can then respond to the first Action by calling a method in the Utils module, and then the Utils module has the code to call the second Action when the server response comes back.

Related

How to avoid action chains

I'm trying to understand Flux pattern.
I believe that in any good design the app should consist of relatively independent and universal (and thus reusable) components glued together by specific application logic.
In Flux there are domain-specific Stores encapsulating data and domain logic. These could be possibly reused in another application for the same domain.
I assume there should also be application-specific Store(s) holding app state and logic. This is the glue.
Now, I try to apply this to imaginary "GPS Tracker" app:
...
When a user clicks [Stop Tracking] button, corresponding ViewController raises STOP_CLICK.
AppState.on(STOP_CLICK):
dispatch(STOP_GEOLOCATION)
dispatch(STOP_TRACKING)
GeolocationService.on(STOP_GEOLOCATION):
stopGPS(); this.on = false; emit('change')
TrackStore.on(STOP_TRACKING):
saveTrack(); calcStatistics(); this.tracking = false; emit('change')
dispatch(START_UPLOAD)
So, I've got an event snowball.
It is said that in Flux one Action should not raise another.
But I do not understand how this could be done.
I think user actions can't go directly to domain Stores as these should be UI-agnostic.
Rather, AppState (or wherever the app logic lives) should translate user actions into domain actions.
How to redesign this the Flux way?
Where should application logic go?
Is that correct to try to keep domain Stores independent of the app logic?
Where is the place for "services"?
Thank you.
All of the application logic should live in the stores. They decide how they should respond to a particular action, if at all.
Stores have no setters. The only way into the stores is via a dispatched action, through the callback the store registered with the dispatcher.
Actions are not setters. Try not to think of them as such. Actions should simply report on something that happened in the real world: the user interacted with the UI in a certain way, the server responded in a certain way, etc.
This looks a lot like setter-thinking to me:
dispatch(STOP_GEOLOCATION)
dispatch(STOP_TRACKING)
Instead, dispatch the thing that actually happened: STOP_TRACKING_BUTTON_CLICKED (or TRACKING_STOPPED, if you want to be UI-agnostic). And then let the stores figure out what to do about it. All the stores will receive that action, and they can all respond to it, if needed. The code you have responding to two different actions should be responding to the same action.
Often, when we find that we want dispatch within a dispatch, we simply need to back up to the original thing that happened and make the entire application respond to that.

Error Handler with Flux

I have a React.js application that I am refactoring to use the Flux architecture, and am struggling to figure out how error handling should work while sticking to the Flux pattern.
Currently when errors are encountered, a jQuery event 'AppError' is triggered and a generic Error Handling helper that subscribes to this event puts a Flash message on the user's screen, logs to the console, and reports it via an API call. What is nice is I can trigger an error for any reason from any part of the application and have it handled in a consistant way.
I can't seem to figure out how to apply a similar paradigm with the Flux architecture. Here are the two particular scenarios I'm struggling with.
1) An API call fails
All of my API calls are made from action creators and I use a promise to dispatch an error event (IE 'LOAD_TODOS_FAILED') on failure. The store sees this event and updates it's state accordingly, but I still dont have my generic error behavior from my the previous iteration (notifications, etc).
Possible resolution:
I could create an ErrorStore that binds to the 'LOAD_TODOS_FAILED' action, but that means every time I have a new type of error, I need to explicitly add that action to the ErrorStore, instead of having all errors be automatically handled.
2) Store receives an unexpected action
This is the one I'm really confused about. I want to handle cases when an action is dispatched to a Store that does not make sense given the Store's current state. I can handle the error within the Store to clean up the state, but still may want to trigger an error that something unexpected happen.
Possible resolutions:
Dispatch a new action from the store indicating the error.
I believe Stores are not suppose to dispatch actions (let me know if I'm wrong), and I still have the same issue as with an API error above.
Create a ControllerView for Error Handling that subscribes to every Store
I could define an errors property on every store, then have a View watching every Store and only act on the errors property. When the errors property is not null, it could dispatch new actions, etc. The disadvantages are that I need to remember to add every Store to this view whenever new ones are created, and every store has to have an error property that behaves the same way. It also does nothing to address API call failures.
Does anyone have a suggested approach for a generic Error Handler that fits into the Flux architecture?
TL;DR
I need to handle errors in most Action Creators and Stores. How do I setup consistent error handling that will occur for any type of generic error?
API call fails
If you want to avoid listing every error action in the ErrorStore, you could have a generic APP_ERROR action, and have properties of that action that describe it in more detail. Then your other stores would simply need to examine those properties to see if the action is relevant to them. There is no rule that the registered callback in the stores needs to be focused on the action's type, or only on the type -- it's just often the most convenient and consistent way of determining if an action is relevant.
Store receives an unexpected action
Don't issue a new action in response to an action. This results in a dispatch-within-a-dispatch error, and would lead to cascading updates. Instead, determine what action should be dispatched ahead of time. You can query the stores before issuing an action, if that helps.
Your second solution sounds good, but the dangerous thing you mentioned is "When the errors property is not null, it could dispatch new actions, etc" -- again, you don't want to issue actions in response to other actions. That is the path of pain that Flux seeks to avoid. Your new controller-view would simply get the values from the stores and respond by presenting the correct view.

Flux Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch

My code
https://gist.github.com/ButuzGOL/707d1605f63eef55e4af
So when I get sign-in success callback I want to make redirect,
redirect works through dispatcher too.
And I am getting Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.
Is there any hack to call action in the middle ?
I don't see where in the gist that you posted you are doing the redirect. I only see the AUTH_SIGNIN and AUTH_SIGNIN_SUCCESS actions, and they look pretty straightforward.
But no, there is no hack to create an action in the middle of a dispatch, and this is by design. Actions are not supposed to be things that cause a change. They are supposed to be like a newspaper that informs the application of a change in the outside world, and then the application responds to that news. The stores cause changes in themselves. Actions just inform them.
If you have this error, then you need to back up and look at how you're handling the original action. Most often, you can set up your application to respond to the original action, accomplish everything you need to do, and avoid trying to create a second action.
You can make it work by "scheduling" the next action instead of calling it directly, here is an example code:
// instead of doing this
Dispatcher.dispatch(...);
// go like this
setTimeout(function() {
Dispatcher.dispatch(...);
}, 1);
This will cause your next dispatch to be called later out of the current dispatch process, and no error will happen.
If your dispatch code is on a callback any kind of other async operation that will work as well (for example in a response for an Ajax request).
I'm using this style to make some forms respond to generic data here and I'm facing no issue, at least the way I'm using it.
you can user the "defer" option in the dispatcher.
In your case it would be like:
Dispatcher.dispatch.defer(...);
You can check if the dispatcher is dispatching, such as:
if(!MyDispatcher.isDispatching()) {
MyDispatcher.dispatch({...});
}

Best practice for combining requests with possible different return types

Background
I'm working on a web application utilizing AJAX to fetch content/data and what have you - nothing out of the ordinary.
On the server-side certain events can happen that the client-side JavaScript framework needs to be notified about and vice versa. These events are not always related to the users immediate actions. It is not an option to wait for the next page refresh to include them in the document or to stick them in some hidden fields because the user might never submit a form.
Right now it is design in such a way that events to and from the server are riding a long with the users requests. For instance if the user clicks a 'view details' link this would fire a request to the server to fetch some HTML or JSON with details about the clicked item. Along with this request or rather the response, a server-side (invoked) event will return with the content.
Question/issue 1:
I'm unsure how to control the queue of events going to the server. They can ride along with user invoked events, but what if these does not occur, the events will get lost. I imagine having a timer setup up to send these events to the server in the case the user does not perform some action. What do you think?
Question/issue 2:
With regards to the responds, some being requested as HTML some as JSON it is a bit tricky as I would have to somehow wrap al this data for allow for both formalized (and unrelated) events and perhaps HTML content, depending on the request, to return to the client. Any suggestions? anything I should be away about, for instance returning HTML content wrapped in a JSON bundle?
Update:
Do you know of any framework that uses an approach like this, that I can look at for inspiration (that is a framework that wraps events/requests in a package along with data)?
I am tackling a similar problem to yours at the moment. On your first question, I was thinking of implementing some sort of timer on the client side that makes an asycnhronous call for the content on expiry.
On your second question, I normaly just return JSON representing the data I need, and then present it by manipulating the Document model. I prefer to keep things consistent.
As for best practices, I cant say for sure that what I am doing is or complies to any best practice, but it works for our present requirement.
You might want to also consider the performance impact of having multiple clients making asynchrounous calls to your web server at regular intervals.

Cancel controller action from Initialize()

I have come across a scenario where I have some initialization code on my conrtoller, which might identify an invalid state which will demand some user interaction.
There for, I want to redirect the customer to another page/action if that occurs. Since I don't want the initial action to run if I hit this invalid state, I want to cancel the whole request including the action.
Is this possible? We have figured out that one way to solve it is to use a Filter which reads out from Context.Items if it should cancel the action, but is there another, easier way?
I started reading this and immediately thought "Context and Filter" :-)
I think that is the cleanest way to do it... That said, you could also do
Context.UnderlyingContext.Response.Redirect("someotherurl");
Which internally throws a ThreadAbortException so it skips all other code.

Resources