reactjsinputaddeventlistenerkeyup

How to remove input value upon clicking enter


I'm implementing a function that uses the value of an input to determine which function is going to be executed. After each time a value is inserted I want the input to clear so the user doesn't have to do it that manually every time. I succeeded to clear the value upon clicking but afterwards both the if and else statements are triggered simultaneously and I don't understand why.

useEffect(() => {
  let scannerInput = document.getElementById('scannerInput');
  scannerInput?.focus();

  scannerInput?.addEventListener("keyup", function(event) {
    if(event.key === "Enter"){
      if (event.currentTarget.value.toString() === ArticleData[randomNumber].artNr.toString()){
        addAmount();
        setContainerAnimation('none');
      } else {
        containerAnimationFunction();
      }
      event.currentTarget.value = "";
    }
  })
}, [amount]);

Solution

  • You're adding too many event listeners. You're adding an event listener after your component mounts and any time amount updates.

    The correct approach would be to have your event listener in an useEffect that only creates your event once, and removes it before your component unmounts. If I'm understanding your problem correctly you don't need the [amount] dependency in your useEffect, since you only need to listen to the enter key.

    useEffect(() => {
      const eventHandler = (event) => {
        document.getElementById('scannerInput')?.focus();
    
        if(event.key === "Enter"){
          if (event.currentTarget.value.toString() === ArticleData[randomNumber].artNr.toString()){
            addAmount();
            setContainerAnimation('none');
          } else {
            containerAnimationFunction();
          }
          event.currentTarget.value = "";
        }
      }
    
      document.getElementById('scannerInput')?.addEventListener("keyup", eventHandler);
    
      return () => {
        document.getElementById('scannerInput')?.removeEventListener("keyup", eventHandler);
      }
    }, []);