'useEffect triggering before useState [duplicate]
I have a form that is supposed to register every input (through useState) and constantly check if that is valid (through useEffect), but that console.log always seems to return a outdated check so I think it is first checking if it's valid and then registering the change.
//SAVING INPUTS
const [values, setValues] = useState({})
function handleChange(e) {
setValues({ ...values, [e.target.id]: e.target.value })
}
//VALIDATING FORM
const [validation, setValidation] = useState({ emailValid: false })
useEffect(() => {
handleEmail()
console.log(validation)
}, [values])
function handleEmail() {
const { email } = values
const emailIsValid = /[\w]+@[\w]+.(com|br|net)/.test(email)
setValidation({ ...validation, emailValid: emailIsValid })
}
This is the form's input field:
<div className="inputbox">
<label htmlFor="email">E-mail</label>
<input type="text" id="email" required onChange={e => handleChange(e)} />
</div>
Solution 1:[1]
Youre code is fine. Because console.log(validation) runs before setValidation({ ...validation, emailValid: emailIsValid }).
updating the state is asynchronous https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
Solution 2:[2]
Use another useEffect to display validation
useEffect(() => {
console.log(validation)
}, [validation])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | L'amjed Bouhouch |
| Solution 2 | Vugar Taghiyev |
