Hello I have a question about fetch call inside componentDidMount. Here's an example code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState({ hits: [] });
useEffect(async () => {
const result = await axios(
'https://hn.algolia.com/api/v1/search?query=redux',
);
setData(result.data);
}, []);
return (
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
);
}
export default App;
Here
useEffect(()=>{},[]);
This is the same as componentDidMount.
Inside useEffect we fetch data from server and store it into data. Then data is used to render items to page as <li> elements.
My question is, does fetch call (ie. axios) get executed AFTER App component gets mounted the first time? If so, how does data get populated in time for the first rendering?
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
My understanding is, since data is populated AFTER the first mount, it won't be available for rendering?
Maybe I'm misunderstanding the difference between MOUNTING and RENDERING?
Can someone correct me because the above code obviously does work.
Thanks.