Fix login redirect: wait for currentUser before navigating
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+7
-23
@@ -1,9 +1,9 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate, useLocation, Link } from 'react-router-dom';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function Login() {
|
||||
const { login } = useAuth();
|
||||
const { login, currentUser } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const successMessage = location.state?.message || '';
|
||||
@@ -12,23 +12,12 @@ export default function Login() {
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleLogin = async (e) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
const { error: err } = await login(email, password);
|
||||
if (err) {
|
||||
setError('Invalid email or password.');
|
||||
setLoading(false);
|
||||
return;
|
||||
useEffect(() => {
|
||||
if (currentUser) {
|
||||
navigate(currentUser.role === 'team' ? '/dashboard' : '/my-projects', { replace: true });
|
||||
}
|
||||
// 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) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
@@ -37,13 +26,8 @@ export default function Login() {
|
||||
if (err) {
|
||||
setError('Invalid email or password.');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
// Small delay to let onAuthStateChange set currentUser
|
||||
setTimeout(() => {
|
||||
// Will be redirected by ProtectedRoute if they go to /dashboard or /my-requests
|
||||
navigate('/dashboard');
|
||||
}, 300);
|
||||
// Navigation handled by useEffect watching currentUser
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user