jackjoesmith
jackjoesmith

Reputation: 971

can't get countdown timer to work

I have to set a countdown to the 15th of every month. I'm able to successfully get the difference value needed to countdown to the 15th. But after that I honestly don't know what I'm doing.

After calculating the difference, I calculate the days, hours, min, secs.

I get the error Cannot read property Days Null

export default React.createClass({
tick: function(){

var currentDate = new Date();
var date_till_15 = new Date()

if(currentDate.getDate() < 15){
    var days_till_15 = 15 - currentDate.getDate();
    date_till_15 = new Date(date_till_15.setDate(currentDate.getDate() + days_till_15 ));
}else if(currentDate.getDate() > 15){
    date_till_15 = new Date(date_till_15.setMonth(currentDate.getMonth() + 1));
    date_till_15 = new Date(date_till_15.setDate(15));
}
    var difference =  date_till_15 - currentDate;
    var daysLeft = 0, hoursLeft = 0, minutesLeft = 0, secondsLeft = 0;
    if(difference > 0){
        daysLeft = Math.floor( difference / (1000*60*60*24) );
        difference -= daysLeft * (1000*60*60*24);
        hoursLeft = Math.floor( difference / (1000*60*60) );
        difference -= hoursLeft * (1000*60*60);
        minutesLeft = Math.floor( difference / (1000*60) );
        difference -= minutesLeft * (1000*60);
        secondsLeft = Math.floor( difference/1000 );

      this.setState({
        days: daysLeft,
        hours: hoursLeft,
        minutes: minutesLeft,
        seconds: secondsLeft
      });
  } else {
        clearInterval( this.timeInterval );
        this.setState({expired: true});
    }
},

componentDidMount: function(){
    this.timeInterval = setInterval( this.tick.bind(this), 1000);
},

render() { 
    return <div> <div> this.state.days</div>

           </div>
}

Upvotes: 0

Views: 60

Answers (1)

tobiasandersen
tobiasandersen

Reputation: 8680

The first time your component renders, this.state doesn't exist, which is why this.state.days throws that error. To solve this, you could either create an initial state, or only render the value if this.state exists:

render() { 
    return <div>{this.state && this.state.days}</div>
}

Upvotes: 1

Related Questions