0

Im trying to make a state that will contain all the pressed keys.

function App() {

  const [inputArray, setInputArray] = useState(["After me should be a list of keys: "]);

  function keyDownListener(e){
    console.log(`Key: ${e.key} with keycode ${e.keyCode}. Array: ${inputArray} `);

    let clonedArray = [...inputArray];
    clonedArray.push(e.key);
    setInputArray(clonedArray);
  }
 
  useEffect(() => {
    document.addEventListener('keydown', keyDownListener);
    }, []);

  return (
    <div className='app' >
      {inputArray}
    </div>
  );
}

But for some reason it always has only one last pressed key altho I tried a lot of ways to update the state the result was always the same. So the output always looks like this: After me should be a list of keys: Alt and it does react to me pressing keys but its just always showing only one key instead of adding new ones like that: After me should be a list of keys: AltAltAltAlt

2 Answers 2

1

Update your function to this

function keyDownListener(e) {
  console.log(`Key: ${e.key} with keycode ${e.keyCode}. Array: ${inputArray} `);
  setInputArray(prevArray => [...prevArray, e.key]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I feel like I tried million ways of updating that damn array and nothing worked but, well, your way is working. Thank you
0

Your useEffect is missing a dependency (keyDownListener) so it always refers to the first keyDownListener (which itself refers to the first inputArray).

You can fix your problem like this for instance :

  useEffect(() => {
    function keyDownListener(e){
      console.log(`Key: ${e.key} with keycode ${e.keyCode}. Array: ${inputArray} `);

      let clonedArray = [...inputArray];
      clonedArray.push(e.key);
      setInputArray(clonedArray);
    }

    document.addEventListener('keydown', keyDownListener);
    
    return () => document.removeEventListener('keydown', keyDownListener);
  }, [inputArray]);

4 Comments

This somehow made an infinite loop and browser console is just spaming keyDownListener(e) with diffirent keys now. Answer from Pratik Wadekar seems to work tho
You are right. keyDownListener has to be created with "useCallback" or be created right inside useEffect. I will edit my answer
Works too, I wonder which way is more correct now, thank you
Either way are correct ;) It just depends on the context or the style you prefer ;) The most important is to understand why those solutions fix your pb ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.