I am playing around with reactjs and here is what I am doing: Am working on retrieving data from an API and displaying the data Using axios to make a call to the API. I know that axios calls are asynchronous and promise based.
My understanding is that in react 'setState' can only be called after the component has mounted ( which happens in componentDidMount ). So the call to the API is made in 'componentDidMount'
what I am not clear is : why does this work and why do I get the data displayed ?
I was reading here that 'render' gets fired before 'componentDidMount' completes
So given the fact that 'render' is before 'componentDidMount' I am confused why the data loads and shows up fine ?
I had also looked at this site where it makes use of some flags to determine if data has loaded or not and then decides whether to show a spinner or not I did not have to do any such thing as well So while it does display data , I am sure there is more to this ...
Here is the code:
class StudentsPage extends React.Component{
constructor(props){
super(props);
this.state = {
isLoaded: false,
studentListArray: []
}
}
componentDidMount(){
/** now get results from api call and need to set the result to the state of this class */
/** setting state MUST happen using setState and no other way - this is important */
/** NOTE below call to setState will ONLY modify the attribute 'studentListArray' of state
* if there were other attributes / properties in state they would not get impacted / modified
* so setState is more like setters for individual properties
* you can change multiple properties in one setter OR call setState for each property you want to change !
*/
/** define the endpoint to be called */
const baseUrl = process.env.REACT_APP_API_URL + "/studentList/";
axios.get(baseUrl).then(({data}) => {
this.setState(
{ studentListArray: data }
);
})
}
render(){
return(
<React.Fragment>
<table className="table">
<thead>
<tr>
<th>Sudent ID</th>
<th>Student subject</th>
</tr>
</thead>
<tbody>
{this.state.studentListArray.map((student) => {
return (<tr>
<td>{student.id}</td>
<td>{student.subject}</td>
</tr>);
})}
</tbody>
</table>
</React.Fragment>
);
}
}