I think due to React's useState asynchronous nature, I am running into an issue where when I try to update the state quickly it does not work. I know of course I am doing something wrong, but not sure what. Basically I have a component that when it loads, might fire off a callback in rapid succession, in this case two times. This should update the state of the parent component by appending to the array in the state system. But it fails. I understand why it fails, but not what I am doing wrong.
export const Foo = () => {
const [selected, setSelected] = React.useState<any[]>([]);
const onSomeFastAction = (value: any) => {
console.log(`adding ${value} to selected`)
console.log(selected) // Prints [] on first AND second logs
setSelected([...selected, value])
}
React.useEffect(() => {
// Only the second value is ever in the array and this only logs once
console.log(selected);
}, [selected])
return (
<CrazyFastComponentThing
onThingThatHappens={onSomeFastAction}
/>
)
}
CodePudding user response:
You must use a function to set newState:
export const Foo = () => {
const [selected, setSelected] = React.useState<any[]>([]);
const onSomeFastAction = (value: any) => {
console.log(`adding ${value} to selected`)
console.log(selected) // Prints [] on first AND second logs
setSelected(prevState => {
const newState = [...prevState];
newState.push(value);
return newState;
}
}
React.useEffect(() => {
// Only the second value is ever in the array and this only logs once
console.log(selected);
}, [selected])
return (
<CrazyFastComponentThing
onThingThatHappens={onSomeFastAction}
/>
)
}