In React, I'm making an async API call, updating a React state, and then running a function in a following .then()
that uses that React state. However, the function runs without the updated state data, even though it's in a then
. Why is this?
You can see below, how I originally wrote my function. But sortArray
runs without the updated foods
state.
const [foods, setFoods] = useState([]);
api
.getFood('fruits')
.then((res) => {
setFoods(res);
})
.then(() => sortArray(foods));
Instead, I needed to do the below code, that is, write an updater useEffect that waits until the state is set, and then runs the sortArray
function, which for some reason has the updated foods
state.
const [foods, setFoods] = useState([]);
api
.getFood('fruits')
.then((res) => {
setFoods(res);
})
.then(() => setNeedsSorting(true));
// cue up sort function
useEffect(() => {
if (needsSorting) {
setNeedsSorting(false);
sortArray();
}
}, [needsSorting, sortArray]);
const sortArray = useCallback(() => {...sorts the foods array...})
Why is all this necessary? And how does this successfully grab the updated state, when the original code couldn't?
Thanks in advance for the help.