Home > Mobile >  Is there a good way of adding the "new" value to the array
Is there a good way of adding the "new" value to the array

Time:02-05

const [value, setValue] = useState(0);
const [array, setArray] = useState([1, 2]);


const handleKeyDown = (event) => {
    setValue(3);
    setArray([...array, value]);
};

Here i would expect the new array to be [1, 2, 3]

Instead im getting [1, 2, 0]

I now know why this happens, but are there any good ways off working around it?

CodePudding user response:

value will not be updated to 3 until the next re-render, so it's still the initial value (0) when setArray is called. You should assign the value you want to a regular variable and then use that for both.

const handleKeyDown = (event) => {
    const newValue = 3;
    setValue(newValue);
    setArray([...array, newValue]);
};

CodePudding user response:

the problem here is that value is not updated yet it will become '3' but in the next render you can simple add it directly :

setValue(3); // if you need to updated value for the next render
setArray([...array, 3]);
  • Related