Last active
April 9, 2018 15:51
-
-
Save rockymeza/1bcba0f2b326df0677138ec055967a86 to your computer and use it in GitHub Desktop.
Basic TimeProvider implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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