i have added a form validation. when there is no value in fields it works fine on submit. in case if i added valid data to the form field on submit the errors not clearing. not able to understand the issue.
here is my code :
const App = () => {
const { values, onChangeHandler, onSubmitForm, errors } =
FormValidator(ValueValidator);
console.log('errors', errors);
return (
<div>
<form
name="contactform"
className="contactform"
autoComplete="off"
onSubmit={onSubmitForm}
>
<label htmlFor="username" className={errors.username ? 'error' : ''}>
<input
id="username"
name="username"
autoComplete="off"
onChange={onChangeHandler}
value={values.username}
placeholder="Name"
type="text"
/>
</label>
<p>{errors.username && 'user name is required'}</p>
<div>
<label htmlFor="email" className={errors.email ? 'error' : ''}>
<input
placeholder="Email"
autoComplete="off"
onChange={onChangeHandler}
value={values.email}
type="email"
name="email"
id="email"
/>
</label>
</div>
<label className="message" htmlFor="message">
<textarea
placeholder="Message"
autoComplete="off"
name="message"
id="message"
></textarea>
</label>
<div>
<button type="submit">Send</button>
</div>
</form>
</div>
);
};
The issue is occurring because your not actually resetting
let errors = initialErrorsProps;
In valueValidator.tsx like you think you are.
When you do
errors.email = 'Email name required';
You're actually updating is the reference to the initialErrorsProps const. So you'll see when you resubmit after failed validation, errors is already filled with the previous values.
This occurs because objects are passed by reference. More details are here: https://stackoverflow.com/a/13104500/7528450
A simple solution would be just to set your object at the beginning of the method:
let errors = {
username: '',
email: '',
};