Reputation: 1367
I might be making a silly mistake but I have this REST API output that i am consuming in UI through React and I am partially getting the output. When i console log, i get the output for ( testRows is data in AJAX - this.setState({testRows: data});) :
this.state.testRows.Type as 'Application Performance'
but when i do this.state.testRows.Names[0] to print first value i.e. desc2, i face an error. What is the correct way to display or print array values of JSON in react?
{
"Names": [
"desc2",
"desc3"
],
"Result": 0,
"Type": "Application Performance",
"dateTime": [
"2016-07-26 20:35:55",
"2016-07-26 20:35:55"
]
}
ReactJS :
var App = React.createClass({
getInitialState: function () {
return {
testRows: []
};
},
componentWillMount: function (event) {
$.ajax({
type: "GET",
crossDomain: true,
url: /details/3,
success: function(data) {
this.setState({testRows: data});
}.bind(this),
error:function(data) {
alert("Data sending failed");
}
});
},
render: function() {
console.log(this.state.testRows.Type); ~~ I get the output
console.log(this.state.testRows.Names[0]); ~~ Error
return (
);
}
});
var element = document.getElementById('content');
ReactDOM.render(React.createElement(App), element);
Upvotes: 0
Views: 2667
Reputation: 9408
You are trying to console log the Names
from your render method.
Render method gets called immediately after the component is mounted, which means that your ajax has not completed by that time and so your state does not have Names
and hence when you try to access an undefined
error is thrown.
But after your ajax is completed and state is set, and when render
is called again the if
clause satisfies and your code works as the names
is now available.
Upvotes: 1