Created
February 26, 2016 17:42
-
-
Save evanrs/7a97ecb31bb8f187b4a9 to your computer and use it in GitHub Desktop.
Poll at interval or on window focus, throttle between interval and focus events.
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, { Component, PropTypes } from 'react' | |
import throttle from 'lodash/throttle'; | |
import attempt from 'lodash/attempt'; | |
class Poll extends Component { | |
static propTypes = { | |
throttle: PropTypes.number, | |
interval: PropTypes.number, | |
onFocus: PropTypes.func, | |
onInterval: PropTypes.func | |
}; | |
static defaultProps = { | |
interval: 60000, | |
throttle: 30000 | |
}; | |
throttle = | |
throttle(attempt, this.props.throttle, { trailing: false }); | |
componentDidMount() { | |
this.mount(this.props); | |
} | |
componentWillReceiveProps(props) { | |
if (props.onInterval !== this.props.onInterval || | |
props.onFocus !== this.props.onFocus) { | |
this.unmount(); | |
this.mount(props); | |
} | |
} | |
componentWillUnmount () { | |
this.unmounting = true; | |
this.unmount(); | |
} | |
mount(props) { | |
let { interval, onFocus, onInterval } = props; | |
if (onFocus) { | |
this.onFocus = this.throttle.bind(this, onFocus); | |
global.addEventListener('focus', this.onFocus); | |
} | |
if (onInterval) { | |
this.onInterval = this.throttle.bind(this, onInterval); | |
this.interval = global.setInterval(this.onInterval, interval); | |
} | |
} | |
unmount() { | |
this.throttle.cancel(); | |
this.onFocus && | |
global.removeEventListener('focus', this.onFocus); | |
this.interval && | |
global.clearInterval(this.interval); | |
} | |
render () { | |
return this.props.children | |
} | |
} | |
export default Poll; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment