Desi Gabrielle Desi Gabrielle - 3 years ago 153
React JSX Question

printing objects onto view from axios get request on reactjs

I'm currently trying to print values from objects from the response data I am getting back from axios get API on reactjs.

I currently have 7 objects with value arrays inside all of them coming back on the DOM via console.log. I've tried to use the .map function to print values from the objects but keep getting undefined error or this.state.thisData.map is not a function.

Any recommendations on how to print various values from different objects?

module.exports = class ViewConsultTest extends React.Component {
constructor(props) {
super(props);


this.state = {
consultData: []

}
}


componentDidMount() {
var _this = this;
this.serverRequest =
axios.get('/api/Consults/viewConsultData')
.then(function(results){
console.log(results.data);
_this.setState({
consultData: results.data
});
})
}



render () {
return(
<div>
<h3>Returning Users:</h3>
{this.state.consultData.consultNotes.map(function(consult) {
return (
<div>{consult.noteText}</div>
);
})}
</div>
);
}
}


screenshot of the objects i am trying to access

Answer Source

Update the render method as, because initially you are not getting data and render method is breaking its flow.

render () {
    var consultNotes= this.state.consultData.consultNotes;
    consultNotes = consultNotes ? consultNotes : [];
    return(
        <div>
          <h3>Returning Users:</h3>
            {consultNotes.map(function(consult) {
          return (
            <div>{consult.noteText}</div>
          );
         })}
        </div>
  );
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download