I am trying to implement a login check. I want to check if the user is logged in before he/she can view the page. If not, then redirect the user to the login page. When the user is redirected to the login page, I want to display a toast message - "Login Required". Here is what I have done -
import Layout from "../../../Component/Layout/Layout";
import { Navigate } from "react-router-dom";
import { useAuth } from "../../../Context/AuthContext";
import { toast } from 'react-hot-toast';
function Dashboard() {
const {isLoggedIn, userId, userType, login, logout} = useAuth();
if (!isLoggedIn) {
toast.error("Login Required");
return <Navigate to="/login" />;
}
return (
<Layout>
<h1>Dashboard</h1>
</Layout>
)
}
export default Dashboard;
useAuth() is a custom hook that I have created.
The issue is that, when I am redirected, the toast message is not being shown. It is only visible when it is about to disappear. How do I fix this?
Edit 1: I read that adding a timeout before navigating would help. I tried that but it didn't work.
Hopefully, this will resolve your issue