Search code examples
flux

How to handle server/request errors in flux?


I've called an action creator from a component to create/edit a resource, which in turn sends an API request to a server. How should I handle cases where the server is down, or returns an error? I want any relevant components to be notified of the success/failure.

My current ideas are to:

  1. Dispatch COMMENT_FAILED, COMMENT_SUCCESS actions to the comment store, which then notifies the components somehow?

  2. Use promises within the initiating component to catch errors from the action call and respond/render them appropriately.

Which is better? Why?

This has been previously asked in React+Flux: Notify View/Component that action has failed?, but the only proposed solution is to use Promises as in 2. I can certainly do that, but it seems... un-Flux-like.


Solution

  • What I usually do is create an error reducer specific to my container/component. For instance, if the user filed a login I would dispatch the error to my login reducer as follows.

    export default function dispatchError() {
          return function(dispatch) {
               dispatch({
                    type: 'LOGIN_ERROR',
                    payload: 'You entered an incorrect password'
               });
          }
     }   
    

    Now in your instance this would be very similar. Anytime there is a failed request dispatch to your reducer.