Skip to content

Instantly share code, notes, and snippets.

@cjcenizal
Created January 19, 2016 00:06
Show Gist options
  • Save cjcenizal/369f5063ed66e2152714 to your computer and use it in GitHub Desktop.
Save cjcenizal/369f5063ed66e2152714 to your computer and use it in GitHub Desktop.
Redirect 401 in React
// In the View component
componentWillUpdate(nextProps) {
// Each view or subview should check the results of
// its API requests to make sure the user is authorized.
handleUnauthorizedErrors([
nextProps.someApiError,
], () => {
// If not, then the user should be redirected to the
// login location, with a subsequent redirect back
// to the current location in the app.
const route = nextProps.location.pathname;
nextProps.promptLogInThenRedirect(route);
});
}
// handleUnauthorizedErrors.js
export default (errors, onError) => {
function checkForError(error) {
// NOTE: This depends upon 401 being used as
// the Unauthorized status code.
if (error && error.code === 401) {
onError();
return true;
}
return false;
}
if (!Array.isArray(errors)) {
return checkForError(errors);
}
// This can handle multiple error statuses.
for (let i = 0; i < errors.length; i++) {
const error = errors[i];
if (checkForError(error)) return true;
}
};
// RouteActions.js
promptLogInThenRedirect: pathAfterLogIn => {
const pathWithoutLeadingSlash = pathAfterLogIn.replace(/^\//g, '');
// Store a path to redirect to once the user logs in.
const queryString = Url.makeQuery({redirect: pathWithoutLeadingSlash});
return replaceState(null, 'http://www.loginhere.com', queryString);
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment