I have a simple authentication form, for which I have written a block of code which checks if the password in the password field, is the same as the password given in the Confirm password field. Now as you can see in the code below, if this condition is not fulfilled, the "Error" state is updated to "Test" and then it's logged to the console. Problem is, the first time I hit submit, it logs <empty string> to the console. What am I missing here?
import { useState } from "react";
import { Button, Card, Form } from "react-bootstrap";
import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth } from "../firebase";
import { useNavigate } from "react-router-dom";
const SignUp = () => {
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [passwordConf, setPasswordConf] = useState("");
const [error, setError] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
if (password != passwordConf) {
setError("Test");
console.log(error);
} else {
await createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
console.log(user);
// navigate("/log-in");
})
.catch((error) => {
const errorCode = error.code;
const errorMsg = error.message;
console.log(errorCode, errorMsg);
});
}
};
return (
<Card style={{ width: "20rem" }}>
<Card.Header>
<Card.Title className="text-center">Sign up</Card.Title>
</Card.Header>
<Card.Body>
<Form>
<Form.Group controlId="email" className="mb-3">
<Form.Label>E-mail address</Form.Label>
<Form.Control
type="email"
placeholder="Enter your e-mail"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group controlId="pword" className="mb-3">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Form.Group controlId="pwordConf" className="mb-3">
<Form.Label>Confirm your password</Form.Label>
<Form.Control
type="password"
value={passwordConf}
onChange={(e) => setPasswordConf(e.target.value)}
/>
</Form.Group>
<Button
type="submit"
variant="primary"
className="w-100"
onClick={handleSubmit}
>
Create account
</Button>
</Form>
</Card.Body>
</Card>
);
};
export default SignUp;
CodePudding user response:
setState functions in react are async. It means that your values are not updated immediately.
In order to fix it, you have 2 options:
- Use a new variable as the current value of the error state and log that variable:
if (password != passwordConf) {
const newError = "Test";
setError(newError);
console.log(newError);
}
- Using useEffect:
if (password != passwordConf) {
setError("Test");
}
useEffect(() => {
if(error !== '') {
console.log(error);
}
}, [error]);