Created
November 12, 2017 12:01
-
-
Save tomfa/08fd094415e336f297a7ac6497a47d02 to your computer and use it in GitHub Desktop.
React interval HoC
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
import { connect } from 'react-redux'; | |
const mapStateToProps = ({ refreshThing }) => { | |
return { | |
refreshInterval: 60000, | |
refreshEnabled: true, | |
}; | |
}; | |
const mapDispatchToProps = dispatch => { | |
return { | |
updateStuff: () => dispatch({ type: 'UPDATE_STUFF' }), | |
}; | |
}; | |
export default connect(mapStateToProps, mapDispatchToProps)( | |
WithAutoRefresh(ComponentExample, { | |
getInterval: props => props.refreshInterval, | |
isEnabled: props => props.refreshEnabled, | |
onRefresh: props => props.updateStuff(), | |
}), | |
); |
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
import React from 'react'; | |
function withInterval(WrappedComponent, { getInterval, isEnabled, onRefresh }) { | |
return class extends React.Component { | |
constructor(props) { | |
super(props); | |
this.intervalId = null; | |
} | |
clearRefresh() { | |
if (this.intervalId) { | |
clearInterval(this.intervalId); | |
this.intervalId = null; | |
} | |
} | |
enableRefresh() { | |
this.clearRefresh(); | |
this.intervalId = setInterval( | |
() => onRefresh(this.props), | |
getInterval(this.props), | |
); | |
} | |
componentDidMount() { | |
if (isEnabled(this.props)) { | |
this.enableRefresh() | |
} | |
} | |
componentWillUnmount() { | |
this.clearRefresh(); | |
} | |
componentWillReceiveProps(nextProps) { | |
if (isEnabled(this.props)) { | |
this.enableRefresh() | |
} else { | |
this.clearRefresh(); | |
} | |
} | |
render() { | |
return <WrappedComponent {...this.props} />; | |
} | |
}; | |
} | |
export default withInterval; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment