I have a Register form Component and I want every time the submit button clicked, it will reset the errors validation object and fill with the new one. Since setErrors({})
is an async
function, how to do the next validation flow after the state resetting is really done?
const [name, setName] = React.useState('');
const [email, setEmail] = React.useState('');
const [errors, setErrors] = React.useState<any>({});
function handleSubmit() {
setErrors({}); // the resetting part
// Do belows after setErrors({}) is really done
let newErrors = {};
if (name.trim() === '') {
newErrors = {...newErrors, name: 'Name cannot be empty'};
} else if (name.trim().length < 3) {
newErrors = {
...newErrors,
name: 'Name length cannot be less than 3 characters',
};
}
if (email.trim() === '') {
newErrors = {...newErrors, email: 'Email cannot be empty'};
} else if (
!/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email)
) {
newErrors = {...newErrors, email: 'Email is not valid'};
}
setErrors(newErrors);
}
<Button
mode="contained"
style={{borderRadius: 0}}
contentStyle={{padding: 10}}
uppercase={false}
onPress={handleSubmit}>
Daftar
</Button>