I've got a clock function that gets time and renders out the hours, minutes and seconds, and I'm trying to update the data on screen in real time, but for some reason my setInterval function isn't doing what I expect.
I thought react's render method is supposed to render data in real time. Do I need ajax for this? Can anyone offer some advice?
var CityRow = React.createClass({
render: function() {
var currentdate = new Date();
function getTime() {
// get local time based on the UTC offset
this.hours = currentdate.getUTCHours() + parseInt(this.props.UTCOffset);
// correct for number over 24, and negatives
if( this.hours >= 24 ){ this.hours = this.hours - 24; }
if( this.hours < 0 ){ this.hours = this.hours + 12; }
// add leading zero, first convert hours to string
this.hours = this.hours + "";
if( this.hours.length == 1 ){ this.hours = "0" + this.hours; }
// minutes are the same on every time zone
this.minutes = currentdate.getUTCMinutes();
// add leading zero, first convert hours to string
this.minutes = this.minutes + "";
if( this.minutes.length == 1 ){ this.minutes = "0" + this.minutes; }
this.seconds = currentdate.getUTCSeconds();
}
window.setInterval(function () {
getTime();
}, 1000);
return(
<div className="city-row" ref="cityRow">
<span className="city-time">{this.hours}:{this.minutes}:{this.seconds}</span>
</div>
</div>
)
}
});
The official React Docs describe exactly what you need (and even explains why you should do it as described):
--> React Docs: State and Lifecycle
Example on CodePen:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
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