I'm encountering an issue with React Router where I'm trying to implement authentication for my application using React Router's Route components. I have an Auth component that checks the user's authentication status by making an asynchronous request to my server's /users/check-auth endpoint. If the user is authenticated, it should render the protected routes using , otherwise, it should redirect to the login page.
This is my Auth.jsx
function Auth() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const navigate = useNavigate();
useEffect(() => {
const checkAuth = async () => {
try {
const response = await axios.get(`${base}/users/check-auth`, {
withCredentials: true,
});
if (response.status === 200) {
setIsLoggedIn(true);
}
} catch (error) {
setIsLoggedIn(false);
}
};
checkAuth();
}, [navigate]);
return isLoggedIn ? <Outlet /> : <Login />;
}
These are my Routes
function App() {
return (
<Provider store={store}>
<Toaster richColors position="top-center" />
<Router>
<Routes>
<Route path="/signup" element={<Register />} />
<Route path="/login" element={<Login />} />
<Route element={<Auth />}>
<Route path="/" element={<Home />} />
<Route path="/user-details" element={<UserDetails />} />
</Route>
</Routes>
</Router>
</Provider>
);
}
export default App;
and this code is in Login.jsx
const handleSubmit = async (e) => {
e.preventDefault();
const userDetails = {
email: data.email,
password: data.password,
};
try {
const response = await axios.post(`${base}/users/login`, userDetails);
toast.success(response.data.message);
Cookies.set("aToken", response.data.data.accessToken, {
expires: 1,
path: "",
});
navigate("/");
} catch (error) {
toast.error(error.response.data.message);
}
};
after this didn't work, i tried different appraoch using reducer where i set isloggedin status to true after a successfull login and then use it in auth.jsx to check whether the user is authenticated or not, this was the code for it:
const { isLoggedIn } = useSelector((state) => state.user);
let token = Cookies.get("aToken") || isLoggedIn;
if (!token) {
return <Login />;
}
return <Outlet />;
also there is this problem in the above code aswell. It didn't work if i used only cookies or only isLoggedIn. I had to use both in order to make it work. https://daisyui.onrender.com/ this was achieved using both cookies and islogged in. i want to understand what is the problem. i think it has something to do with batch updates of react or maybe something else that i dont know of. Please help me with it.