I'm trying to validate an input field for emailaddresses. The actual validation works, the state updates and everything around it works. However, I noticed a strange behaviour once a false email is validated.
NOTE: I changed the name of my states and attributes to make it more generic and readable.
<TextField
label = {emailFieldAttributes.label}
type = {emailFieldAttributes.type}
onChange = { event => {
onChangeHandler(event)
}}
id = {emailFieldAttributes.id}
value = {state.value_email}
InputProps = {{
autoComplete: 'off',
inputMode: 'string'
}}
error = {state.error.value}
ref = {ref}
></TextField>
function onChangeHandler(event)
{
if (event.target.id.includes('cc'))
{
setState({...state, value_cc: event.target.value});
}
else if (event.target.id.includes('body'))
{
setState({...state, value_body: event.target.value});
}
else
{
setState({...state, value_email: event.target.value});
}
if (state.error != initialErrorState
)
{
resetEmailTooltip();
}
}
function resetEmailTooltip()
{
setEmailStateValues(
{
...state,
error: resetErrorState
});
}
In the submit buttons' onClick, I run the validation and it works as it updates the state correctly and shows a tooltip. In fact, the onChange works as it's supposed to except for 1 slight undesired behaviour. Whenever a validation does return false and updates the state.error, a tooltip is shown. The next time a change is done on the input field the first event only triggers resetEmailTooltip();
and does not the update the state value.
Stepwise - current behaviour
- Add email address with incorrect format: 'test@.test'
- Press submit
- Validation
- Tooltip shown
- First change in the inputField by pressing down e.g. 'b' on the keyboard leads to tooltip being removed
- 2nd event of pressing down 'b' would lead to 'test@b.test'
Stepwise - desired behaviour
- Add email address with incorrect format: 'test@.test'
- Press submit
- Validation
- Tooltip shown
- First change in the inputField by pressing down e.g. 'b' on the keyboard leads to tooltip being removed and leads to 'test@b.test'
What I don't understand is why it requires a second event to trigger the state update? Do I have something wrong regarding my thought process when it comes to how onChange is fired?