0

What's wrong with my code? In any case console.log is "email ready to submit". How can I get errorEmail status?

const ContactForm = () => {
  const [errorEmail, setErrorEmail] = useState(false);

  const validateEmail = (data) => {
    const emailString = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (emailString.test(data)) {
      setErrorEmail(false);
    } else {
      setErrorEmail(true);
    }
  }


  const submitForm = (e) => {
    e.preventDefault();
    const formData = e.target;

    validateEmail(formData.email.value);

    if (errorEmail) {
        console.log('email error');
    } else {
        console.log('email ready to submit');
    }
  }
Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
thetiti
  • 95
  • 2
  • 7
  • [This](https://stackoverflow.com/questions/54119678/is-usestate-synchronous) might be helpfull – Harikrishnan Jun 16 '20 at 13:46
  • `setState` is async so you need to wait till it's finished before you use the updated. this might help: https://stackoverflow.com/questions/53898810/executing-async-code-on-update-of-state-with-react-hooks – Red Baron Jun 16 '20 at 13:47

1 Answers1

0

You might be logging before the state is updated, that's because the state is updated asynchronously.

You can use the useEffect hook and check the modified state inside it:

useEffect(() => {
    if (errorEmail) {
        console.log('email error');
    } else {
        console.log('email ready to submit');
    }
}, [errorEmail])

const submitForm = (e) => {
    e.preventDefault();
    const formData = e.target;

    validateEmail(formData.email.value);

    // if (errorEmail) {
    //     console.log('email error');
    // } else {
    //     console.log('email ready to submit');
    // }
}
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32