Reputation: 3880
I'm using react native and i want to get the "Time ago" in near real time. (ex: 1 minute ago, 3 hours ago etc.)
My problem is i am facing difficulties to tell my app it must refresh the date every X seconds.
componentDidMount(){
setInterval(() => {
this.refresh()
},30000)
}
refresh = () => {
content = <Text note>{this.getTimeAgo()}</Text>
return content
}
getTimeAgo = () => {
//doing stuff to format then
return TimeAgo
}
Actually it works but only once (the first 30 seconds and after it no longer update (getTimeAgo() is no longer called).
So i don't know why it call getTimeAgo() once , i need it to be called at least every 30 seconds.
What i have missed ?
thanks
Upvotes: 0
Views: 440
Reputation: 53598
Where would it return to? Set up a state value (probably called timeAgo
?), make the component update that state value every 30 seconds, so that React retriggers render()
, and then in your render function tap into that value to present it to your users:
class TimerThing extends React.Component {
constructor(props) {
super(props);
this.state = {
timeAgo: 0
};
}
componentDidMount() {
setInterval(() => this.setTimeAgo(),30000)
}
render() {
return <Text note>{this.state.timeAgo}</Text>
}
setTimeAgo() {
var timeAgo;
// ...do computy things...
this.setState({ timeAgo });
}
}
Upvotes: 1
Reputation: 5926
Have you tried using setState
and then using the value of that item in state as the content of your component?
Something like this:
setInterval(() => {
this.setState({timeAgo: this.getTimeAgo()});
}, 30000);
And in the return
of the render
method, include
{this.state.timeAgo}
where you want the time to be displayed.
Upvotes: 0