I am doing a project which needs to encapsulate the letter has been typed by the user
const { useState, useEffect } = React;
function App() {
const [usedLetter,setUsedLetter] = useState([])
useEffect(()=>{
window.addEventListener('keydown', handleKeydown);
return () => {
window.removeEventListener('keydown',handleKeydown);
}
},[])
function handleKeydown(event){
const letter = event.key;
setUsedLetter(usedLetter => [...usedLetter,letter])
console.log(usedLetter);
}
return (
<div className="App">
<p>Used letter : {usedLetter}</p>
</div>
);
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
This block of code produced a strange behavior. When I monitor state from react developer tool, everything was normal. The result show on the browser was normal. But when it came to the console, specifically console.log(usedLetter);
the value stored in usedLetter
was nothing even after I had hit a number of character. I have tried to access usedLetter
through useEffect
and it worked but it was inconvenient because I had to break the flow and accessed it outside of event listener callback
Can anyone tell me why this happen and how can I work around to get the real usedLetter
(the one show on the browser) inside the event listener callback ?
Thanks a million