Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJS: State variable not updating as expected

So I’m learning react and as a practise exercise, I made a basic add user app. The data should only be inserted in case in both input fields are valid. The problem is even if validations fails, the app still enters the data into the field. I’m not sure why because I have explicitly added the condition:

const onSubmit = (event) => {
    event.preventDefault();
    validateUser(newUser);
    if (!showModal.display) {
      console.log(showModal.display);
      props.onAddingNewUser(newUser);
      setNewUser({
        username: "",
        age: "",
      });
    }
  };

Here is the link to sandbox for my app: https://codesandbox.io/s/beautiful-wilbur-j35mmi

Try clicking submit button without entering any data and you’ll see it still populated the list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m still learning React so it would be great if someone can elaborate what I’m doing wrong here.

Thanks!

>Solution :

the reason for that is every time you close the error box you convert display to false again, so no matter what in the end the if statmet:

  validateUser(newUser);
    if (!showModal.display){
...more code
}

will always be true because even if the user is not valid when you close the error box display will be false again and the if statement will run.

if you want a way around you can return false or true from the validateUser there are more ways to solve this, this is just one way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading