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.
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.