Home > Blockchain >  Listen for Change ONLY ONCE on a React Controlled Input
Listen for Change ONLY ONCE on a React Controlled Input

Time:04-19

I am attempting to emit a socket event on user input but I want the event to be emitted ONLY ONCE when the value of the input changes in state and another event to be emitted ONCE when the value is cleared.

const [text, setText] = useState("");

...

useEffect(()=> {
      if (text) {
        // EMIT EVENT
        console.log("input has value emit event", text);
      } else {
        console.log("input has no value emit event");
      }
}, [text]);

...

const handleChange = e => {
    setText(e.target.value);
}

...

<Input type="text" value={text} onChange={handleChange} />

I am able to accomplish this but my code emits on every keystroke. My requirement is for both events to emit only once.

  • One when there is a value in state
  • Another when there is no value in state

CodePudding user response:

Do the check in handleChange instead, so that you can compare the prior value to the new value.

const handleChange = e => {
    const newText = e.target.value;
    setText(newText);
    if (newText && !text) {
        console.log("input has value emit event", text);
    } else if (!newText && text) {
        console.log("input has no value emit event");
    }
}
  • Related