Please take a look at this code snippet.
function App() {
useEffect(() => {
document.addEventListener('keydown', onKeyDown);
}, []);
const onKeyDown = e => {
setKeyMap({ ...keyMap, [e.keyCode]: true });
};
const [keyMap, setKeyMap] = useState({});
// JSON.stringify gives only one key-value pair
return (
<div className="App">
<h1>Hello {JSON.stringify(keyMap)}</h1>
</div>
);
}
So using useEffect
, I am adding an eventlistener to keydown
event only once. This is similar to componentDidMount apparently since this occurs only once.
In the event handler for keydown event, I am trying to add all keycodes which were pressed to be true.
So say I press 'a', then my keyMap should look like this:
{
"65": true
}
Now if I press 'b', then my keyMap should look like this:
{
"65": true,
"66": true
}
But what's happening is this:
{
"66": true
}
Why am I unable to mutate the previous state and add to it? Like I previously had "65" as the key, but when I press another key on my keyboard, suddenly this "65" key-value disappears. That is at any given point, only one
key-value pair exists for some reason. I want to be able to add to this object(keyMap object I mean) as many times as I want. Is the ...
operator(spread) not working?