Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't access object's properties within object in react

Tags:

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>
        );
}
like image 582
totalnoob Avatar asked Mar 04 '18 22:03

totalnoob


2 Answers

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.

like image 200
David L. Walsh Avatar answered Sep 21 '22 12:09

David L. Walsh


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

like image 21
Xirb Avatar answered Sep 19 '22 12:09

Xirb