Vignesh Veeran
Vignesh Veeran

Reputation: 95

React : state property initialized in constructor to some value but returns undefined when rendered

In the following component, I have a state property which is initialized in constructor to a value of 5. But when i am using it inside render then it returns undefined. I don't understand why.

constructor() {
  super();

  this.state = {
    loadcomplete: false,
    twitterfeed: {
      techcrunch: [],
      laughingsquid: [],
      appdirect: []
    },
    tweetCount: 30
  };
}

render() {
  let { tweetCount } = this.state.tweetCount;
  console.log(tweetCount, "tweetcount");
  return(<div></div>)
}

Upvotes: 0

Views: 424

Answers (1)

Tyler Sebastian
Tyler Sebastian

Reputation: 9458

Should be unpacking this.state instead of this.state.tweetCount

let { tweetCount } = this.state.tweetCount is ~ equivalent to let tweetCount = this.state.tweetCount.tweetCount

use

let { tweetCount } = this.state;

edit: and yes, as other people have pointed out, you should be correctly passing props into the constructor and passing it to the parent class via super - but that's not why tweetCount is undefined

Upvotes: 2

Related Questions