DEV Community

Maxim Romanov for JetRockets

Posted on • Originally published at jetrockets.pro

How to handle 401 unauthorized error in a Redux React application

In response to a client request, the server may return a 401 Unauthorized error. You must correctly catch it, for example, clear the state and redirect to the authorization page. To solve this problem, we wrote a custom Middleware which, in our opinion, is the best solution.

import * as actions from 'actions';

const authInterceptor = ({ dispatch }) => (next) => (action) => {
  if (action.status === 401) {
    dispatch(actions.removeJwt());
  } else {
    next(action);
  }
};

Top comments (1)

Collapse
 
abishekku profile image
Abishek Kumar

i am try to dispatch multiple actions on my component using useEffect. but it throws error 401 unauthorized. when i dispatch one api it works fine .but on multiple api ith throws error. i used several methods to like map function , setTimeout , promise.all, .then all get throws error.