What do I need to do to make doSomethingWithItems()
wait until after fetchItems()
has completed?
const [items, setItems] = useState();
const fetchItems = async () => {
try {
let responseData = await sendRequest(`${process.env.REACT_APP_BACKEND_URL}/items/user/${userId}`);
setItems(responseData.items);
} catch (err) {}
};
const doSomethingWithItems = () => {
const filteredItems = items.filter(x => x.title === 'something');
setItems(filteredItems);
}
useEffect(() => {
fetchItems(); // ** WAIT FOR THIS TO FINISH BEFORE MOVING ON **
doSomethingWithItems();
}, []);
3
Answers
Since
fetchItems
isasync
, it returns aPromise
. Which you can follow with.then()
:Or, more expanded syntax to better understand the structure:
However, your next problem is tracking state. Note that
doSomethingWithItems
depends onitems
. But state is not updated immediately. Instead of updating state infetchItems
, return the new value and pass it todoSomethingWithItems
:Try this
React documents that if you are calling asynchronous code from within a
useEffect()
that you are best to define anasync
function INSIDE theuseEffect()
and then call that function. This is what yah yaha’s solution is doing, though because it uses the Immediately Invoked Function Expression (IIFE) approach, it might not be obvious as:However, as David’s answer hints at: the next problem is that the "set state function" of
useState()
is asynchronous but it does not return a Promise. So this means that your code cannotawait
it or.then()
it. You have NO WAY of knowing when the call tosetItems()
will actually finish…you cannot wait for it.Good news! React has a solution for that — React will RE-RENDER a component after its state gets updated by the "set state function".
And as David suggests, you can have React do something in (react)ion to a specific state variable being modified with use of a
useEffect()
— "when theitems
state variable has a new value, here’s some code I want to run".React is a pretty simple system overall. But it takes a bit of wrapping your head around state variables, rendering, and JavaScript’s asynchronous code execution.
I strongly encourage all of my friends (and make it a requirement of all of my coworkers) to watch the video JavaScript: Understanding the Weird Parts multiple times. Especially the parts about Synchronous and Asynchronous code execution (time links are in the video description).