'useState not setting value
I am trying to make a calculator, but when i click the number buttons, the screen doesnt update. I checked the handler, and it seems like it should work. I also logged the calc(see code for reference) and it is not updating. What is wrong?
import React, {useState} from 'react';
import Screen from './screen.js'
import Button from './button.js'
import ButtonBox from './buttonBox.js'
const btnValues = [
["C", "+-", "%", "/"],
[7, 8, 9, "X"],
[4, 5, 6, "-"],
[1, 2, 3, "+"],
[0, ".", "="],
];
const CalcBody =() => {
{/*res as in result */}
let [calc, setCalc] = useState({
sign: "",
num: 0,
res: 0,
});
const numClickHandler = (e) => {
e.preventDefault();
const value = e.target.innerHTML;
if (calc.num.length < 16) {
setCalc({
...calc,
num:
calc.num === 0 && value === "0"
? "0"
: calc.num % 1 === 0
? Number(calc.num + value)
: calc.num + value,
res: !calc.sign ? 0 : calc.res,
});
}
console.log(calc.num)
};
return (
<div className="wrapper">
<Screen value={calc.num ? calc.num : calc.res} />
<ButtonBox>
{btnValues.flat().map((btn, i) => {
return (
<Button
key={i}
className={btn === "=" ? "equals" : ""}
value={btn}
onClick={numClickHandler
}
/>
);
})}
</ButtonBox>
</div>
);
}
export default CalcBody;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
