Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Listen for Change ONLY ONCE on a React Controlled Input

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading