I can't seem to access data that's part of an object within an object. here I'm trying to access likes in profile which would otherwise be fine using vanilla javascript to print out this.state.data.profile.likes
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
var x = {
"notifications": 12,
"profile": {
"likes": 5
}
};
this.setState({
data: x
});
}
render() {
const {notifications, profile} = this.state;
return (
<div>
<span>Notifications {notifications}</span>
<span>Likes {profile.likes}</span>
</div>
);
}
Before mounting - and on the initial render - your state looks like this:
{
data: {}
}
After mounting - on the second render - your state looks like this:
{
data: {
notifications: 12,
profile: {
likes: 5
}
}
}
You're trying to access this.state.profile.likes
which doesn't exist. Presumably you mean to access this.state.data.profile.likes
which does exist, but only on the second render.
I noticed this while also trying to fix the same problem. The constructor should be:
constructor(props) {
super(props);
this.state = {
data: {
profile: {}
}
};
}
Always initialize objects within objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With