I've been working with optimistic updates in a React+Flux application and saw two things:
- What happens if a user attempts to close the window when exists some uncompleted actions. For example in Facebook, a message appears in the wall even if wasn't really persisted (this is what optimistic updates does, a more responsive application for the user). But, if a user post in the wall and immediately close the application (on logout or window close), the post could fail and he would not be alerted.
- I don't like the idea of Stores managing his own entities (for example messages) and the situation of the action triggered for persiste a message (loading, succesfull, failed?). It mixes things.
So I work on this and create an ActionStore to manage the state of the actions triggered by the components. Here is the source code and here is a live demo.
It works more or less like this:
- The root of the components hierarchy (container in redux) fetch the nextId of a new action and pass it to his childs like props (this is ugly).
- A child component fires an action: it keeps the actionId for ask it to the store after and call the action creator.
- The action creator creates a new Action and returns a function to the middleware.
- The function returned from the Action creates a new Promise with the API call and dispatches an action of type XX_START.
- The ActionStore listen to the XX_START action and saves it.
- The child component receives the new state and find the action with the saved id and ask it the current situation: loading, successful or failed.
I've done this mainly for separate the state of the "entities" from the state of the actions, but allows retrigger actions with the same payload too (this could be useful when we receive 500 response status if the server is temporarly down or if the user loose signal).
Also, having an store of actions allows to easily ask if they are pending actions before the user logout or close the window.
Note: I'm working with a Single Application Page web app against a Rest API, I'm not think to use this on server-side rendering
It's a viable option create a ActionStore or I'm breaking some Redux/Flux foundations? This could end the posibility of use React Hot Reloading and Time traveling?
You should answer with no mercy, I've probably done a bunch of ugly things but I'm learning React/Redux.