I have a simple React Component, and am trying to display a nested JSON object in render.
// React Component
class NodeDetail extends React.Component {
constructor(props) {
super(props);
const node = {};
this.state = {
node
}
}
componentDidMount() {
Node.getNode(this.props.node_id).then((result) => {
console.log(result.data);
this.setState(() => ({node: result.data}));
}).catch(function(error) {
// TODO: handle error
});
}
render() {
return (
<div>
{this.state.node.node_status.name}
</div>
);
}
};
export default NodeDetail;
This is the JSON(stored in result.data) getting returned from a rails API(some fields removed for brevity):
{
"id":1234,
"name":"some-node",
"created_at":"2018-05-18T15:23:24.012Z",
"hostname":"some-host",
"ip":"10.XXX.XXX.XXX",
"mac":"24:6e:96:XX:11:XX",
"node_status":{
"id":2,
"name":"Parked"
}
}
When I access the root level attributes in React with this.state.node.mac , it returns 24:6e:96:XX:11:XX.
When I try to access the name attribute in node_status using this.state.node.node_status.name, I get the the following error:
Uncaught TypeError: Cannot read property 'name' of undefined
I have also tried this.state.node['node_status'].name, and same error.
Why can't I access this object in the JSON, when clearly it is there?
this.state.node.node_statusreturn?this.state.node.node_statusreturnsundefined. But it is actually present. Verified this withconsole.log(result.data);node_status, like this,this.setState(() => ({node: result.data.node_status}));and then dothis.state.node.namethis.state.node.mac(which you wrote worked), did you do that within therendermethod as well?