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

React JS Array state just keeps reseting instead of adding new values

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

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 :

Update your function to this

function keyDownListener(e) {
  console.log(`Key: ${e.key} with keycode ${e.keyCode}. Array: ${inputArray} `);
  setInputArray(prevArray => [...prevArray, e.key]);
}
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