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
2
Answers
Setting state in React is asynchronous. This means the
setData
function 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 log
data immediately after setting it.You may want to actually check the data in your render function or just after your
useEffect
hook if you have one.Example:
You’re going to show the
data
on the component, so you can’t useuseRef
, so usinguseEffect
is the best way I can see.check this video
@Kobra’s answer answers the question –
setState
is asynchronous and might not reflect immediate changes of thestate
. AnduseEffect
is a great tool to synchronous components (includingstate
) with an external system.As it is unclear how you use your function with the
fetch()
method; a way to check the changed value of astate
is to put it in auseEffect
, withdependencies
specified. For example,And the data should populate the HTML once the state is updated – React would re-render the component when state changes (according to React’s documentation).