Reputation: 2539
I'm creating a form builder in react. On a simple text field, I need to:
currentValue
currentValue
is changed, validate itHere's my code:
const TextInput = ({ props }) => {
const [currentValue, setCurrentValue] = useState(props.initialValue);
const [validationState, setValidationState] = useState(false);
const validate = () => {
if (!currentValue) {
setValidationState(false);
}
else {
setValidationState(true);
}
}
useEffect(() => {
validate();
}, [currentValue]);
useEffect(() => {
emitter.emit('textInputChange', { currentValue, validationState});
}, [validationState]);
}
However, I have this problem now that if I only depend upon validationState
to emit changes, as soon as TextInput
becomes valid, emit stops. I need to emit on each change.
But if I depend on currentValue
too, then since the validationState
is not sync, I can get invalid state. In other words, the currentValue
might be valid, but I emit invalid
from the previously non-updated validationState
.
How should I solve this?
Upvotes: 2
Views: 264
Reputation: 12787
I think you don't need state validationState
, just update like this with one useEffect
:
const validate = (value) => {
if (!value) {
return false;
}
return true;
};
useEffect(() => {
const isValid = validate(currentValue);
emitter.emit("textInputChange", { currentValue, validationState: isValid });
}, [currentValue]);
Upvotes: 2