Skip to content

Instantly share code, notes, and snippets.

@tomfa
Created November 12, 2017 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomfa/08fd094415e336f297a7ac6497a47d02 to your computer and use it in GitHub Desktop.
Save tomfa/08fd094415e336f297a7ac6497a47d02 to your computer and use it in GitHub Desktop.
React interval HoC
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(),
}),
);
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