I am pulling some data from Facebook API,
const response = await axios.get('API ENDPOINT')
setData(response.data); // Assuming the data is in the response.data
console.log(response.data) //printing values
console.log('Data copied to state:', data); // Log the state after update
console.log(response.data) This one logs data correctly as JSON object in console
console.log('Data copied to state:', data) gives an empty array.
Accessed from HTML Element
{data?.length > 0 && (
<ul>
{data.map((item, index) => (
<li key={index}>
{/* Access item properties here */}
{item.email} - {item.last_name}
</li>
))}
How to get data populated to data object to print in HTML Element
Setting state in React is asynchronous. This means the
setDatafunction doesn't immediately mutate the provided state but creates a pending state transition. This is the reason why you're seeing an empty array when youconsole logdata immediately after setting it.You may want to actually check the data in your render function or just after your
useEffecthook if you have one.Example:
You're going to show the
dataon the component, so you can't useuseRef, so usinguseEffectis the best way I can see.check this video