I created a login page. I am trying to authenticate a user by sending the message from the backend after verifying if the user exists in the database. Everything is working fine just one problem is that when I login with correct credentials I have to click twice on the submit button for it to work.
import React, { useState } from "react";
import axios from "axios";
const Login = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [auth, setAuth] = useState("Wrong");
const [mssg, setMssg] = useState("");
const handleUser = (e) => {
setUsername(e.target.value);
};
const handlePassword = (e) => {
setPassword(e.target.value);
};
const login = (e) => {
e.preventDefault();
const user = { username, password };
console.log(user);
axios
.post("http://localhost:5000/auth", user)
.then((res) => setAuth(res.data.message))
.catch((err) => console.log(err));
if (auth === "OK") {
sessionStorage.setItem("user", username);
window.location = "/dashboard";
} else {
setMssg("Invalid Details. Please try again");
}
};
return (
<div>
<form onSubmit={login}>
<input onChange={handleUser}></input>
<input type="password" onChange={handlePassword}></input>
<input type="submit"></input>
</form>
<p id="mssg">{mssg}</p>
</div>
);
};
export default Login;
When i login with correct credentials, it throws the error. But when i submit again with the same correct credentials, then it redirects me to the dashboard.
CodePudding user response:
You can here make usage of the useEffect hook that would help you redirect:
useEffect(()=>{
if (auth === "OK") {
sessionStorage.setItem("user", username);
window.location = "/dashboard";
} else {
setMssg("Invalid Details. Please try again");
}
}, [auth])
here you can see we're passing the auth state as dependencies that would make useEffect call the function we're passing each time auth changes that would allow us to redirect the user whenever he's logged in!
PS: Do not forget to remove the section of code I used inside useEffect
from your login function
CodePudding user response:
It looks like the issue is that the login
function is checking the value of auth
immediately after making the API call, but the API call is asynchronous, so the value of auth
hasn't been updated yet. This is why you need to click the submit button twice - the first time, the API call is made and auth
is updated, but the function exits without checking the updated value. The second time you click the submit button, auth
has already been updated, so the function is able to correctly redirect to the dashboard.
One way to fix this issue is to use the async/await
syntax to make the login
function asynchronous, and then wait for the API call to complete before checking the value of auth
and redirecting if necessary. Here's an example of how you could do that:
const login = async (e) => {
e.preventDefault();
const user = { username, password };
console.log(user);
try {
const res = await axios.post("http://localhost:5000/auth", user);
setAuth(res.data.message);
if (auth === "OK") {
sessionStorage.setItem("user", username);
window.location = "/dashboard";
} else {
setMssg("Invalid Details. Please try again");
}
} catch (err) {
console.log(err);
}
};
With this change, the login
function will wait for the API call to complete before checking the value of auth
and redirecting if necessary. This should fix the issue of needing to click the submit button twice.