I’m trying to redirect users to /feed
after they log in, but even though console.log("Login successful")
prints, the page doesn’t navigate to /feed
. It seems like checkAuth()
isn’t updating the authenticated
state in time for Login.jsx
to recognize it as true
. Am I using async/await incorrectly, or is there an issue with my useEffect dependency on authenticated?
Here’s the relevant code:
Context API methods:
const checkAuth = async () => {
try {
const response = await axiosInstance.get("/authenticate-user");
if (response.data.isAuthenticated) {
setAuthenticated(true);
setUser(response.data.user);
setProfileUrl(`/profile/${response.data.user.id}`);
} else {
setAuthenticated(false);
setUser(null);
}
} catch (error) {
console.error("Error during authentication check:", error.response);
setAuthenticated(false);
setUser(null);
}
};
useEffect(() => {
checkAuth();
}, []);
const handleLogin = async (email, password) => {
try {
await axiosInstance.post("/login", { email, password });
// Check if login was successful
await checkAuth();
console.log("Login successful");
} catch (error) {
console.error("Error during login:", error.response);
toast.error("Invalid Credentials");
}
};
Login.jsx
export default function Login() {
const { authenticated, handleLogin, setAuthenticated } = useContext(AppContext);
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
useEffect(() => {
if (authenticated) {
navigate("/feed");
}
}, [authenticated, navigate]);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
const { email, password } = formData;
await handleLogin(email, password);
setFormData({
email: "",
password: "",
});
setLoading(false);
};
// rest of the code
}
Why isn’t checkAuth()
updating authenticated
in time, and how can I ensure authenticated
is correctly checked before Login.jsx
attempts to navigate?