import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class Clock extends Component {
componentDidMount(){
setInterval(() => (
this.setState(
{ curHours : new Date().getHours()}
),
this.setState(
{ curMins : new Date().getMinutes()}
),
this.setState(
{ curSeconds : new Date().getSeconds()}
)
), 1000);
}
state = {curHours:new Date().getHours()};
state = {curMins:new Date().getMinutes()};
state = {curSeconds:new Date().getSeconds()};
renderHours() {
return (
<Text>{'Hours:'}{this.state.curHours}</Text>
);
}
renderMinutes() {
return (
<Text>{'Minutes:'}{this.state.curMinutes}</Text>
);
}
renderSeconds() {
return (
<Text>{'Seconds:'}{this.state.curSeconds}</Text>
);
}
}
-I'm trying to make an app that can keep track of time kinda like a daily planner. So I need to get the current time in real time during app run time. The app is supposed to tell the user that they have failed to accomplish a certain task in a given time for example. I tried exporting the clock.js and using its functions but only the renderSeconds() is working, the others are only showing blanks.
When you're defining state three times, only the last one is persisted because you're overwriting the previous variable. In addition, your initial state should be declared in a constructor. Add this to the top of your class
constructor() {
this.state = {
curHours:new Date().getHours(),
curMins:new Date().getMinutes(),
curSeconds:new Date().getSeconds(),
}
}