The user is in home page and if he goes to any protected route(cart page, profile page) without authentication he will be Redirecting to login page and after login they must not return to home page, they must go to the current location they were trying to go to when they were redirected, but it returns to the homepage.
<Routes>
<Route path='/' element={<HomeScreen />} />
<Route path='/signin' element={<SignInScreen />} />
<Route path='/signup' element={<SignUpScreen />} />
<Route path='/products/:id' element={<ProductScreen />} />
<Route element={<PrivateRoute />}>
<Route path='/cart' element={<CartScreen />} />
<Route path='/wishlist' element={<WishlistScreen />} />
<Route path='/profile' element={<ProfileScreen />} />
</Route>
</Routes>
const PrivateRoute = () => {
if (!auth.authenticated) {
return <Navigate to='/signin' replace={true} />;
}
return <Outlet />;
};
const Submit = async (e) => {
e.preventDefault();
let data = { email, password };
if (!email || !password) {
setMessage('Please Enter All Fields');
} else {
setLoading(true);
return await axios
.post('/signin', data)
.then((res) => {
if (res.data.message === 'Invalid Credentials') {
setMessage('Invalid Credentials');
setLoading(false);
}
if (res.data.message === 'Logged In') {
setLoading(false);
navigate('/', { replace: true });
}
})
.catch((err) => {
console.log(err);
setLoading(false);
});
}
};