Fix login redirect: wait for currentUser before navigating

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Krao Hasanee
2026-03-26 23:54:20 -04:00
parent d7f89ad0da
commit 8b5494a824
+7 -23
View File
@@ -1,9 +1,9 @@
import { useState } from 'react'; import { useState, useEffect } from 'react';
import { useNavigate, useLocation, Link } from 'react-router-dom'; import { useNavigate, useLocation, Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext'; import { useAuth } from '../context/AuthContext';
export default function Login() { export default function Login() {
const { login } = useAuth(); const { login, currentUser } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
const successMessage = location.state?.message || ''; const successMessage = location.state?.message || '';
@@ -12,23 +12,12 @@ export default function Login() {
const [error, setError] = useState(''); const [error, setError] = useState('');
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const handleLogin = async (e) => { useEffect(() => {
e.preventDefault(); if (currentUser) {
setLoading(true); navigate(currentUser.role === 'team' ? '/dashboard' : '/my-projects', { replace: true });
setError('');
const { error: err } = await login(email, password);
if (err) {
setError('Invalid email or password.');
setLoading(false);
return;
} }
// onAuthStateChange in AuthContext sets currentUser + role → redirect handled below }, [currentUser, navigate]);
};
// After login, AuthContext updates currentUser. Use onAuthStateChange to redirect.
// We rely on ProtectedRoute to handle post-login navigation.
// But we need to redirect on success — watch currentUser via auth state.
// Simplest: redirect after successful login based on profile role.
const handleSuccess = async (e) => { const handleSuccess = async (e) => {
e.preventDefault(); e.preventDefault();
setLoading(true); setLoading(true);
@@ -37,13 +26,8 @@ export default function Login() {
if (err) { if (err) {
setError('Invalid email or password.'); setError('Invalid email or password.');
setLoading(false); setLoading(false);
return;
} }
// Small delay to let onAuthStateChange set currentUser // Navigation handled by useEffect watching currentUser
setTimeout(() => {
// Will be redirected by ProtectedRoute if they go to /dashboard or /my-requests
navigate('/dashboard');
}, 300);
}; };
return ( return (