Here is my repo https://github.com/extrapractice/lambda-calculator/tree/revised
What is going on is when I am using a react hook for useState, it works fine, but however, I set up an event listener on useEffect for when a key is pressed (its a calculator) but for some reason once the key is pressed and the event is fired, the react state is undefined?
Why is this happening and how would I correct this?
const Calculator = (props) => {
const [ display, setDisplay ] = useState('');
useEffect(() => {
window.addEventListener('keydown', handlekeyDown);
// window.addEventListener('keydown', handleEquals);
return () => {
window.addEventListener('keydown', handlekeyDown);
// window.addEventListener('keydown', handleEquals);
};
}, []);
function handlekeyDown(e) {
e.preventDefault();
const current = e.key;
const values = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', '*', '/'];
if (values.includes(current)) {
let value = current;
setDisplay((prev) => prev + value);
}
}
function handleEquals(e) {
const value = e.key
console.log(display)
if (value === '=') {
const solution = math.evaluate(display)
const histEntry = { problem: display, solution: solution };
props.setHistory((prev) => [ ...prev, histEntry ]);
setDisplay(solution);
}
}
function addToString(e) {
console.log(e.target)
let value = e.target.value;
if (value === '=') {
const histEntry = { problem: display, solution: math.evaluate(display) };
props.setHistory((prev) => [ ...prev, histEntry ]);
setDisplay(math.evaluate(display));
} else {
setDisplay((prev) => prev + value);
}
}
display
state is updated? Also, include the code formath.evaluate
. FYI, you have a mistake in the return function of the effect, it should remove the event listener. – Drew Reesemath.evaluate
ismath.js
and returns a number instead of a string. Trying to repro your issue but not successful yet. codesandbox – Drew ReesehandlekeyDown
function was updated. Maybe it is because you definehandlekeyDown
after the effect, thus it is triggered with undefined, then once it becomes defined it's triggered again (now, since in dependency array). Doesn't seem likely this is the case though. – Drew Reese