Based on the code you provided, it seems that you are trying to set the second element of the nums
array as the value of result
. However, when you call setNums([...nums, Number.parseInt(disp)])
, you are actually adding a new element to the nums
array, not modifying the existing one.
Therefore, when you call setResult(nums[1])
, nums[1]
is undefined
, since there is no second element in the nums array until you add it in the previous line. That's why result
is also undefined
.
To set result
to the correct value, you need to use the updated nums
array after adding the new element. Here's one way you could modify the code to achieve that:
const [nums, setNums] = React.useState([5]);
const [result, setResult] = React.useState(0);
let op = "-"
let disp = "5";
if (op === '=') {
const newNums = [...nums, Number.parseInt(disp)]; // create a new array with the added element
setNums(newNums);
setResult(newNums[1]) // set result to the second element of the updated array
}
With this code, result
should now be set to 5
, and console.log(nums)
should return [5, 5]
.