Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native show current time and update the seconds in real-time

I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don't update unless I refresh the page. I also tried using setInterval function in render(), it do got update but it's expensive for CPU. is there a good method to realise the function?

state = {     curTime: null, } render(){     setInterval(function(){this.setState({curTime: new  Date().toLocaleString()});}.bind(this), 1000);     return (         <View>             <Text style={headerStyle.marginBottom15}>Date: {this.state.curTime}</Text>         </View>     ); } 
like image 869
inoutwhy Avatar asked Dec 23 '16 02:12

inoutwhy


People also ask

How do you get current time in seconds in react native?

To get the current datetime in react native has the Date() object it will return every time the current date and time when we use it. we have to just write new Date() and it returns the date object where we get a year, month, date, hours, minutes, and seconds.

How do you show live time in React?

To show current time and update the seconds in real time with React Native, we can use the setInterval function to update the time every second. to call setInterval with a callback that calls setTime with new Date(). toLocaleString() to set time to the current date time string.

How do I change the time every second in React?

To update React component every second with JavaScript, we can use the setInterval function to update a state in the useEffect hook. const [time, setTime] = useState(Date. now()); useEffect(() => { const interval = setInterval(() => setTime(Date.

How do you refresh every 5 seconds in React?

setInterval(() => { window. location. reload(); }, 5000);


1 Answers

Just move setInterval into componentDidMount function.

Like this :

  componentDidMount() {     setInterval(() => {       this.setState({         curTime : new Date().toLocaleString()       })     }, 1000)   } 

This will change state and update every 1s.

like image 101
Nguyên Hoàng Avatar answered Sep 28 '22 07:09

Nguyên Hoàng