Skip to content

Instantly share code, notes, and snippets.

@hasssan
Created July 4, 2017 09:35
Show Gist options
  • Save hasssan/006af954a0cfc02cc8eebacd31633594 to your computer and use it in GitHub Desktop.
Save hasssan/006af954a0cfc02cc8eebacd31633594 to your computer and use it in GitHub Desktop.
Timeago Moment
// source https://github.com/nmn/react-timeago/issues/85#issuecomment-306959939
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
const makeRelative = (dateMoment) => {
if (!dateMoment.isValid()) { return ''; }
return dateMoment.fromNow();
};
const DELAY = 60000; // 1 minute
export default class TimeAgo extends PureComponent {
static propTypes = {
date: PropTypes.oneOfType([
PropTypes.string,
PropTypes.instanceOf(Date),
]).isRequired,
}
constructor(props) {
super(props);
const { date } = props;
const dateMoment = moment(date);
const relative = makeRelative(dateMoment);
this.state = {
dateMoment,
relative,
};
}
componentDidMount() {
const { dateMoment } = this.state;
if (dateMoment && dateMoment.isSame(moment(), 'day')) {
// Only start recalculating if it's a recent date (sometime today)
this.startUpdating();
}
}
componentWillReceiveProps(nextProps) {
const { date } = this.props;
const { date: newDate } = nextProps;
if (newDate !== date) {
const dateMoment = moment(newDate);
if (dateMoment.isSame(moment(), 'day')) {
// This is a recent date (sometime today)
this.startUpdating();
} else {
// This date is old enough that it doesn't need updating
this.stopUpdating();
}
const relative = makeRelative(dateMoment);
this.setState({
dateMoment,
relative,
});
}
}
componentWillUnmount() {
this.stopUpdating();
}
recalculate = () => {
const { dateMoment, relative } = this.state;
const newRelative = makeRelative(dateMoment);
if (newRelative !== relative) {
this.setState({ relative: newRelative });
}
}
startUpdating = () => {
if (this.interval == null) {
this.interval = setInterval(this.recalculate, DELAY);
}
}
stopUpdating = () => {
if (this.interval != null) {
clearInterval(this.interval);
this.interval = null;
}
}
render() {
const { relative } = this.state;
return (
<span>{relative}</span>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment