I have the following setup in my react app:
const [modalReasonInput, setModalReasonInput] = useState("")
const validateReason = () => {
console.log(modalReasonInput)
if (modalReasonInput === "" && record.judgement_result === "fail") {
setError("Field is required")
return false
}
setError("")
return true
}
const handleChange = (value) => {
setModalReasonInput(value)
validateReason()
}
<TextField
type="textarea"
maxLength={1000}
showCounting
rows={6}
value={modalReasonInput}
onBlur={() => validateReason()}
onChange={(e) => handleChange(e.target.value)}
/>
With the above code when I enter first character in the input field a blank/white space is set as value to state modalReasonInput
.
The value is set only if I type another character, but value is set to first character I had typed.
Due to this my validation is failing while typing first character.
How can I update the state value as I type.
CodePudding user response:
It is getting updated as you type but when you try to console.log
the state right after you call setModalReasonInput
you can't see it right away because state updates in React is asynchronous. You can check the state with useEffect
as the state changes:
useEffect(() => {
console.log(modalReasonInput)
}, [modalReasonInput])
CodePudding user response:
The problem is your handleChange
function. If you set the state and perform a validation shortly after it is not guaranteed that the state is available in the next line.
const handleChange = (value) => {
setModalReasonInput(value)
validateReason() // value not guarenteed to be in modalReasonInput state
}
You can either separate state update and validation or directly pass in your value to your validation function validateReason()
:
const validateReason = (value) => {
console.log(value)
if (value === "" && record.judgement_result === "fail") {
setError("Field is required")
return false
}
setError("")
return true
};
const handleChange = (value) => {
setModalReasonInput(value)
validateReason(value)
}