Reactjs – How to manage asynchronous Store operations with Flux

reactjsreactjs-flux

In the Facebook talk on the Flux architecture, Jing mentions at 12:17 that the dispatcher enforces that no actions can be dispatched until the current action is fully processed by the stores.

https://img.youtube.com/vi/nYkdrAPrdcw/0.jpg

The dispatcher here is the main piece that enforces that there's no cascading effects; once an action goes into the store, you can't put another one in until the stores are completely finished processing it.

My question, then, is how do you properly deal with long-running asynchronous operations that might be kicked off from the store (e.g. an Ajax request, or dealing with some other outside async API)—anything that blocks the completion of the action dispatch (for instance, waiting to resolve a promise with the result of an Ajax request) could block UI-generated actions from the user from being dispatched.

Best Answer

In my understanding, asynchronous actions that rely on Ajax, etc. shouldn't block the action from being dispatched to all subscribers.

You'll have a separate action for the user action, like TODO_UPDATE_TEXT in the TodoMVC example and one that gets called when the server returns, something like TODO_UPDATE_TEXT_COMPLETED (or maybe just something more generic like TODO_UPDATE_COMPLETED that contains a new copy of the latest attributes).

In cases where you want to do optimistic updates to show the user the effects of their change immediately, you can update the store in response to the user action immediately (and then once again when the server returns with the authoritative data). If you want to wait on the server, you can have the store only update itself in response to the server-triggered actions.

Related Topic