Created
August 12, 2018 08:02
-
-
Save rcdexta/5e6c4e138abf573a36c05e2e277a94c6 to your computer and use it in GitHub Desktop.
Pollable HOC
This file contains hidden or 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
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