fix: Update all Time components each second (#1214)
* first pass at updating all Time components each second * fix a couple date variable typos * use class style state management instead of hooks * address feedback * lint Co-authored-by: Tom Moor <tom.moor@gmail.com>
This commit is contained in:
@ -4,18 +4,52 @@ import Tooltip from 'components/Tooltip';
|
|||||||
import distanceInWordsToNow from 'date-fns/distance_in_words_to_now';
|
import distanceInWordsToNow from 'date-fns/distance_in_words_to_now';
|
||||||
import format from 'date-fns/format';
|
import format from 'date-fns/format';
|
||||||
|
|
||||||
|
let callbacks = [];
|
||||||
|
|
||||||
|
// This is a shared timer that fires every minute, used for
|
||||||
|
// updating all Time components across the page all at once.
|
||||||
|
setInterval(() => {
|
||||||
|
callbacks.forEach(cb => cb());
|
||||||
|
}, 1000 * 60);
|
||||||
|
|
||||||
|
function eachMinute(fn) {
|
||||||
|
callbacks.push(fn);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
callbacks = callbacks.filter(cb => cb !== fn);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
dateTime: string,
|
dateTime: string,
|
||||||
children?: React.Node,
|
children?: React.Node,
|
||||||
};
|
};
|
||||||
|
|
||||||
function Time({ dateTime, children }: Props) {
|
class Time extends React.Component<Props> {
|
||||||
const date = new Date(dateTime);
|
removeEachMinuteCallback: () => void;
|
||||||
return (
|
|
||||||
<Tooltip tooltip={format(date, 'MMMM Do, YYYY h:mm a')} placement="bottom">
|
componentDidMount() {
|
||||||
<time dateTime={dateTime}>{children || distanceInWordsToNow(date)}</time>
|
this.removeEachMinuteCallback = eachMinute(() => {
|
||||||
</Tooltip>
|
this.forceUpdate();
|
||||||
);
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
componentWillUnmount() {
|
||||||
|
this.removeEachMinuteCallback();
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
return (
|
||||||
|
<Tooltip
|
||||||
|
tooltip={format(this.props.dateTime, 'MMMM Do, YYYY h:mm a')}
|
||||||
|
placement="bottom"
|
||||||
|
>
|
||||||
|
<time dateTime={this.props.dateTime}>
|
||||||
|
{this.props.children || distanceInWordsToNow(this.props.dateTime)}
|
||||||
|
</time>
|
||||||
|
</Tooltip>
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default Time;
|
export default Time;
|
||||||
|
Reference in New Issue
Block a user