Skip to content

Instantly share code, notes, and snippets.

@rcdexta
Created August 12, 2018 08:02
Show Gist options
  • Save rcdexta/5e6c4e138abf573a36c05e2e277a94c6 to your computer and use it in GitHub Desktop.
Save rcdexta/5e6c4e138abf573a36c05e2e277a94c6 to your computer and use it in GitHub Desktop.
Pollable HOC
import React from 'react'
const Pollable = (intervalDurationInSeconds = 60) => {
return Component =>
class extends React.Component {
componentDidMount() {
this.startPolling()
}
componentWillUnmount() {
this.stopPolling()
}
startPolling = () => {
if (this.interval) return;
this.trigger(intervalDurationInSeconds * 1000);
}
onInterval = (fn) => {
this.callbackFn = fn
}
stopPolling = () => {
if (this.interval) {
clearInterval(this.interval)
this.interval = null
}
}
trigger(intervalDurationInMilliSeconds) {
if (this.callbackFn) {
this.interval = setInterval(() => this.callbackFn(), intervalDurationInMilliSeconds)
}
}
getProps() {
return {
...this.props,
startPolling: this.startPolling,
stopPolling: this.stopPolling,
isPolling: Boolean(this.interval),
onInterval: this.onInterval
}
}
render() {
const props = this.getProps()
return <Component {...props}/>
}
}
}
export default Pollable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment