0

Simplified version of the code:

const [nums, setNums] = React.useState([5]);
const [result, setResult] = React.useState(0);

let op = "-"

let disp = "5";

if (op === '=') {
      setNums([...nums, Number.parseInt(disp)]);
      setResult(nums[1]) 
}

I clearly add a second number to the array using a React useState hook, and then use it to set the result, but result returns "undefined"

I should be able to set the result to "5", but instead it sets it to "undefined", console.log(nums) returns [5, 5]

AndreiB
  • 7
  • 3

1 Answers1

1

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].