Ramzan Chasygov Ramzan Chasygov - 3 months ago 42
Javascript Question

Rerender moment.fromNow() in React

How properly refresh moment.from(). I tried set setInterval(this.renderReminders(), 1000) in componentDidMount, but doesn't work, popup error. How solve this issue?



class App extends Component {

renderReminders() {
const { reminders } = this.props;
return (
<ListGroup>
{
reminders.map(reminder => {
return (
<ListGroupItem key={reminder.id}>
<div>{moment(reminder.dueDate, 'DD-MM-YYYY HH:mm').fromNow()}</div>
</ListGroupItem>
) // return
}) // reminders.map
}
</ListGroup>
) // return
} // renderReminders()

render() {
return (
<div className="container">
{ this.renderReminders() }
</div>
) // return
} // render

} // App




Answer Source

I'd say there's easily a couple ways to make timers in React.
One suggestion is to extrapolate Reminder into another react component.

Set the reminderTime in the new component's state and then create a method that usesthis.setState to update the timer.

setState will automatically re-render your component if the state changes.

In componentWillMount you should use setInterval to call a function that wil update the state. In componentWillUnmount you should get rid of the interval with clearInterval.

I didn't test the below code so it's mostly just to get the idea.

class Reminder extends React.Component{
  constructor(props){
      super(props);
      this.state = {
          reminderTime :  moment(this.props.dueDate, 'DD-MM-YYYY HH:mm').fromNow()},
      }
  }

  componentDidMount(){
      // add the interval
      this.interval = setInterval(this.updateReminderTime.bind(this), 3000);
  }

  componentWillUnmount(){
      // remove the interval listener
      clearInterval(this.interval);
  }

  updateReminderTime(){
     this.setState({
        reminderTime : moment(this.props.dueDate, 'DD-MM-YYYY HH:mm').fromNow()}
  }
  
  render(){
      return <div>{this.state.reminderTime }</div>
  }
}

class App extends Component {
renderReminders() {
    return (
      const reminders = this.props.reminders;
      <ListGroup>
        {
          reminders.map(reminder => {
            return (
              <ListGroupItem key={reminder.id}>              
                <Reminder dueDate={reminder.dueDate} />            
              </ListGroupItem>
            ) // return
          }) // reminders.map
        }
      </ListGroup>
    ) // return
  } // renderReminders()
  
  render() {
    return (
      <div className="container">      
        { this.renderReminders() }
      </div>
    ) // return
  } // render
  
 } // App