I’m using React Router to redirect to a login page when user is not logged in, like this:
return (
<main className="App relative">
<Routes>
<Route path="/" element={<AuthLayout />}>
<Route path="/" element={<Login />} />
</Route>
<Route path='/*' element={<PrivateRoute/>}>
<Route path="/*" element={<Layout />}>
<Route path="dashboard" element={<Dashboard />} />
</Route>
<Route path="/*" element={<Layout />}>
<Route path="timeline" element={<TimeLine />} />
</Route>
</Route>
</Routes>
</main>
);
this is my PrivateRoute:
const PrivateRoute = () => {
const [currentUser] = useAtom(currentUserAtom);
const isAuth = (currentUser && currentUser.token);
const prevLocation = useLocation();
var redirectTo = `/login?redirectTo=${prevLocation.pathname}`;
console.log(redirectTo);
return isAuth ? <Outlet /> : <Navigate to={redirectTo} />;
}
export default PrivateRoute;
The problem is that the PrivateRoute executes 3 times, with these results:
/login?redirectTo=/dashboard
/login?redirectTo=/login
/login?redirectTo=/login
And the final redirect page is http://localhost:5173/login?redirectTo=/login
instead of http://localhost:5173/login?redirectTo=/dashboard
What’s wrong?