Flux is awesome, React combined more so.
I have been working with flux and react for a while now. Some of the problems that i faced were around server interaction. Facebook hasn’t talked much about it, the documentation gives no guidelines, except a mention of interaction must be done through action creators.
So i trolled around internet for exloring what other developers have adopted, to find some best practices and solutions to problems i encountered while building react+flux apps.
1. Distinction between reads and writes
This approach is taken from Ian Obermiller’s interview. All writes actually go through actions, the action directly calls the api and do the callback/promise handling. While for reads the component directly talks to the store. There are no actions to fetch data the store directly takes care of it. The store internally might use its cache or make multiple api calls.
The store after fetching the item informs all components about the change and they all can re-render themselves accordingly.
2. All type of interactions through Action creators
All server interactions happens through action creators, they are used to exit the flux flow. Action creators are used to post or get data from server, the action is dispatched when the request is completed. Additionally a service layer may be used for abstraction which contains all api request code and promises can be used to make things pretty.
Why is this better than other approaches?
- All data flows through the dispatcher, this makes for easier debugging.
- Stores remain synchronous , if you let the callbacks leak through to your store they become harder to reason about.
- Avoiding actions firing other actions makes the app simpler.
Personally i found the second approach to be better. Let me know what do you use in you flux app.