Roland Jegorov
Roland Jegorov

Reputation: 819

Handling errors in redux-thunks to do more than notify the user

I've seen numerous articles and live examples of handling errors occurring in redux-thunks by adding ACTION_FAIL/ACTION_SUCCESS and sometimes ACTION_ATTEMPT/ACTION_START. This is great and all, although, all cases I've seen seem to give the user a simple notification like "Oops, this went wrong. Try again!" and go home early.

The case I'm looking for is having a seamless dispatch-error-retry-success transition or at least a better (more maintainable) solution than adding additional action dispatches to every thunk.

An example would be a token expiration. If the token is about to expire or the fail occurred because of an expired token (and logging out is not a good option) then refreshing the token and retrying the request could be a solution without making the user scratch his head.

I'd love to hear:

Upvotes: 0

Views: 323

Answers (1)

Denis Washington
Denis Washington

Reputation: 5622

If you can handle a failure automatically (like in the refresh token example you mentioned), you don't need to dispatch an extra action at all. You can simply retry within the thunk, then dispatch the success action if you recovered successfully.

function doRequest() {
  return dispatch => {
    makeRequest()
      .catch(error => {
        if (isUnauthorizedError(error)) {
          return refreshToken().then(makeRequest);
        }
        throw error;
      })
      .then(
        doRequestSuccess, 
        doRequestFailure
      );
  }
}

The only reason to dispatch an extra "retry" action would be if you would want to communicate the temporary failure in the user interface.

Upvotes: 1

Related Questions