I am trying to update an array in of data that is loaded async from an API (e.g. the user clicks on an item, and it requests the data, and adds it to the list to be displayed a few seconds later.)
I understand that state is not updated immediately, but that is not what is happening, the state has updated, but the code after await still sees the old state.
I can see items
has been updated because the useEffect
fires and outputs the updated array, but then after that, when the await
has finished, the async
code sees items
in its original state.
const [items, setItems] = useState([]);
useEffect(() => {
console.log(`${items.length} items`);
}, [items]);
const addItemFromAPI = async () => {
const name = await getNextItemFromAPI();
// Why is items still referencing the previous copy from BEFORE await?
console.log(`${items.length} existing items`);
setItems([...items, { name }]);
};
Am I doing this completely wrong, is there a pattern for async appending of data to state?
If I change it to useRef()
and then use .current.push()
it works as expected, which leads me to believe something weird is happening with useState
.
https://codesandbox.io/embed/angry-worker-mczcsv?fontsize=14&hidenavigation=1&theme=dark