I'm having trouble forcing a redirect in React Router v6. I have a PrivateRoute and PublicRoute wrapper components that store a url path in local storage if the user is not authenticated Like so:
const PrivateRoutePropTypes = {
children: PropTypes.element.isRequired,
};
function PrivateRoute({
children, // Element to render
}) {
const authenticated = useSelector((state) => state.user.authenticated);
const location = useLocation();
if (!authenticated) {
localStorage.setItem(C.REDIRECT_KEY, location.pathname);
console.log('redirect path set:', localStorage.getItem(C.REDIRECT_KEY));
}
if (authenticated && (localStorage.getItem(C.REDIRECT_KEY) !== null) && !(window.opener)) {
console.log('Authenticated and redirect detected');
const redirectPath = localStorage.getItem(C.REDIRECT_KEY);
localStorage.removeItem(C.REDIRECT_KEY);
console.log('redirectPath: ', redirectPath);
return <Navigate to={redirectPath} />;
console.log('This should not trigger');
}
console.log('redirect not triggered');
return authenticated ? children : <Navigate to="/signin" />;
}
PrivateRoute.propTypes = PrivateRoutePropTypes;
// =================================================================================================
const PublicRoutePropTypes = {
children: PropTypes.element.isRequired,
};
function PublicRoute({
children, // Element to Render
}) {
const authenticated = useSelector((state) => state.user.authenticated);
return !authenticated ? children : <Navigate to="/" />;
}
PublicRoute.propTypes = PublicRoutePropTypes;
If I try to visit a page that is wrapped in <PrivateRoute /> without being signed in, it redirects me to the Sign in page aka "localhost:3000/signin" and saves a redirect path to local storage. However, once I sign in the <PublicRoute /> wrapper redirects me to my root page aka "localhost:3000/". This is however wrapped in the <PublicRoute /> component which I was hoping would detect that I am authenticated and have a redirect saved in local storage and then redirect me to the original page I was trying to access.
The issue is it seems return <Navigate to={redirectPath} /> is ignored as seen by this this log.