Skip to content

Instantly share code, notes, and snippets.

@rockymeza
Last active April 9, 2018 15:51
Show Gist options
  • Save rockymeza/1bcba0f2b326df0677138ec055967a86 to your computer and use it in GitHub Desktop.
Save rockymeza/1bcba0f2b326df0677138ec055967a86 to your computer and use it in GitHub Desktop.
Basic TimeProvider implementation
// We need an impure function that will give us the current time.
// Notice that we return the ISO string version of the date. This is nice
// because it is not a mutable object like `Date` and it is also a
// human readable representation.
const defaultGetTime = () => new Date().toISOString();
export default class TimeProvider extends React.PureComponent {
static defaultProps = {
interval: 500,
};
// start with the current time in state
state = {
currentTime: defaultGetTime(),
};
componentDidMount() {
// on mount, we set up a timer to update our cached time based on
// the interval prop.
this.interval = setInterval(this.updateTime, this.props.interval);
}
componentWillUnmount() {
// don't forget to clean up after ourselves!
if (this.interval) {
clearInterval(this.interval);
}
}
updateTime = () => {
this.setState(() => ({
currentTime: defaultGetTime(),
}));
};
render() {
return (
<TimeContext.Provider value={this.state}>
{this.props.children}
</TimeContext.Provider>
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment