This is a followup question to this question
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.
Here is the code which throws an error:
class StudentsPage extends React.Component{
constructor(props){
super(props);
this.state = {
isLoaded: false,
studentListArray: []
}
}
componentDidMount(){
console.log("<<< inside componentDidMount >>>")
this.setState(
{ studentListArray: getListOfStudents() }
);
}
render(){
console.log("@@@ inside render array is @@@",this.state.studentListArray)
return(
<React.Fragment>
<table className="table">
<tbody>
{this.state.studentListArray.map((student) => {
return (<tr>
<td>{student.id}</td>
<td>{student.subject}</td>
</tr>);
})}
</tbody>
</table>
</React.Fragment>
);
}
}
The axios API call is defined in a separate js file : studentApi.js:
import axios from "axios";
/** define the endpoint to be called */
const baseUrl = process.env.REACT_APP_API_URL + "/studentList/";
/** this function will retrieve the list of students */
export function getListOfStudents(){
console.log("about to call api");
/** if we use axios library then the response payload will always be inside 'data' attribute
* so here we use the {data}
*/
axios.get(baseUrl).then(({data}) => {
console.log(data);
return data;
})
console.log("after making the call to the api")
}
So if I am trying to setState by making a call to a method that calls api using axios I get errors.
The logs show the following :
@@@ inside render array is @@@ []
<<< inside componentDidMount >>>
about to call api
after making the call to the api
@@@ inside render array is @@@ undefined
@@@ inside render array is @@@ undefined
And the exception is :
Uncaught TypeError: Cannot read property 'map' of undefined at StudentListPage.render (StudentListPage.js:75)
I am unable to understand why render is called twice after the api call ? also unable to understand why studentListArray is undefined ? Thanks