Reputation: 347
I have a login authenticating with server side code and whether the login is true or false "loginState" will be set to that. The problem is it is not redirecting at all, even though loginState is set true. Can anyone tell me why this would not be working?
const [login, setLogin] = useState(null);
const [loginState, setLoginState] = useState(false);
const handleOnChange = (e) => {
setLogin({
...login,
[e.target.name]: e.target.value,
});
};
useEffect(() => {
if (loginState == true) {
return <Redirect to="/" />;
}
}, [loginState]);
const handleLogin = () => {
fetch("http://localhost:3005/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: login.username,
password: login.password,
}),
})
.then((res) => res.json())
.then((result) => {
setLoginState(result.login);
});
};
return (
<>
<h1>Login</h1>
<input onChange={handleOnChange} type="text" name="username"></input>
<input onChange={handleOnChange} type="password" name="password"></input>
<button onClick={handleLogin}>Login</button>
</>
);
Upvotes: 0
Views: 44
Reputation: 28654
For Redirect
to work, your component must return it (the component must render it in other words).
Why not move this out of useEffect
:
if (loginState == true) {
return <Redirect to="/" />;
}
and put above return
of the function component say?
Upvotes: 1