In the code below I was expecting that inside the useEffect hook console.log procedure will log the list of the tickets fetched by getAllTickets function because list of the tic
It's not that there's a sequencing issue. It's that the function logging the tickets
value is logging an old value.
Your useEffect
callback is created each time your component function is called, but because your dependency array is empty, only the first of those functions is ever called by useEffect
. That first function closes over the tickets
constant for the call to your component function that created the callback (the first call), in which tickets
is an empty array. So although setTickets
updates your state item, which will cause your component function to be called again, your useEffect
callback (or more accurately, the callbacks it creates) continue to use the old value.
If you want to see the updated array, you can use res
:
React.useEffect(() => {
getAllTickets()
.then((res) => {
const ticketsReceived = [...res]; // Why the shallow copy?
setTickets(ticketsReceived);
console.log(ticketsReceived);
})
.catch((e) => console.log(e));
}, []);