Hossein Fallah
Hossein Fallah

Reputation: 2539

Stuck at react useEffect for a chain of changes

I'm creating a form builder in react. On a simple text field, I need to:

  1. Change currentValue
  2. When currentValue is changed, validate it
  3. When validation is done, emit an event (either valid or invalid)

Here'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

Answers (1)

Viet
Viet

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

Related Questions