Reputation: 51
I have a little problem while displaying server auth response after axios post req. I'm trying to console log server response errorMessage: "please all required fields after form submit. Console keeps showing "undefined". On the server side everything is fine, the network tab shows correct response.
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errors, setErrors] = useState("");
const { getLoggedIn } = useContext(AuthContext);
const history = useHistory();
async function login(e) {
e.preventDefault();
try {
const loginData = {
email,
password,
};
const res = await axios
.post("http://localhost:5000/auth/login", loginData)
.then((result) => {
console.log(result.data);
});
await getLoggedIn();
history.push("/player");
} catch (err) {
console.log(err.data);
}
}
return (
<div className="authWrapper">
<form className="box" onSubmit={login}>
<h1>LOGIN</h1>
<input
autoComplete="off"
className="input"
type="email"
placeholder="Email"
onChange={(e) => setEmail(e.target.value)}
value={email}
/>
<input
autoComplete="off"
className="input"
type="password"
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
value={password}
/>
<button className="submit" type="submit">
{`Log in${" "}`}
<FontAwesomeIcon icon={faArrowRight}></FontAwesomeIcon>
</button>
<Link to="/register">
<button className="changeForm">
{`Register${" "}`}
<FontAwesomeIcon icon={faSync}></FontAwesomeIcon>
</button>
</Link>
</form>
</div>
);
};
export default Login;
<div></div>;
Network login endpoint response
Upvotes: 2
Views: 16982
Reputation: 2353
Just to add something to what has been already said. You don't need to use .then() for promises if you are using await. You can try it this way:
const res = await axios.post("http://localhost:5000/auth/login", loginData)
console.log(res.data);
You'll be waiting for a response from the server. Once you get it, it will be stored in the res constant that you created. Also, you need to add a catch block after every try you write.
Upvotes: 5
Reputation: 1264
Because you are using a promise, an exception is not going to be thrown, so it will not hit your try catch block. You need to add the catch on the promise instead:
const res = await axios
.post("http://localhost:5000/auth/login", loginData)
.then((result) => {
console.log(result.data);
}).catch((error) => {
console.error(error);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Upvotes: 1
Reputation: 5937
You are both waiting for the response using async/await
and use a promise chaining line .post().then().catch()
Try this:
axios.post("http://localhost:5000/auth/login", loginData)
.then((result) => {
console.log(result.data);
await getLoggedIn();
history.push("/player");
})
.catch(err => {
console.log(err)
})
Upvotes: 6