Form validation!

i am wondering, why Mosh in video 14 (validating a Form Using Joi) defined “errors” object again inside validate() in loginForm.jsx, since there were already “errors” object in the state ?? can anybody clarify that to me? appreciate it

@sh2021 Can you explain more about what in confusing about this? What would you have done instead? I’m not sure if you’re asking ‘why did Mosh just initialize errors to {} instead of reading the errors first like in handleChange’ or something different.

we had “errors” in state already and could read it instead of defining it locally again in validate()? got the point now?

In the handleChange method we want to validate just the property that is being changed without touching any other errors that the user can currently see. To make sure we keep those errors that exist, we read in the current errors from the state:

const errors = { ...this.state.errors };

Then we replace the error for the current property and set the state with the errors object.

However, in the validate() method, we are validating the entire form. We’re going to validate each field no matter what, so we don’t care if errors already exist in the state. If our application is working properly, initializing errors as {} would be the exact same result as initializing it with the state like we did in the handleChange method.