Kent Dodds delineates a pretty good approach to auth in a react app here, https://kentcdodds.com/blog/authentication-in-react-applications.
If you're using react-router and useContext in your app just auth that way. Its very convenient to have AuthenticatedApp
and UnauthenticatedApp
as the sides of your ternary in that authentication check.
If for some reason you cant get this in as a ticket and you need to solve redirects quickly in an additive fashion (very little refactoring necessary) use location.state
! Location state lets us pass data on a router action like history.push
.
Assuming you already have redirecting unauthenticated users to an unauthenticated view, the method of fixing bad redirects generalizes to two parts
to
prop or history.push action that is causing that redirect and refactor it to this.<Redirect to='login' /> (could also be) />
or thishistory.push({pathname: 'login', state: { redirectPathName: pathname, redirectSearchParams: search})
const { pathname, search } = useLocation()
// in route declaration
<Redirect to={{pathname: 'login', state: { redirectPathName: pathname, redirectSearchParams: search}} />
handleLogin(username, password) {
const { push } = useHistory();
// handle login stuff
// onSuccess do this
push('/')
}
handleLogin(username, password) {
const { push } = useHistory();
const { state } = useLocation();
// handle login stuff
// onSuccess do this
push(state.redirectPathname ? { pathname: state.redirectPathName, search: state.redirectSearchParams ?? '' } : '/')
}