Last active
December 29, 2018 21:09
-
-
Save davalapar/44e3c038cfa30f92b437681819affebd to your computer and use it in GitHub Desktop.
TimedComponent.jsx
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'; | |
import PropTypes from 'prop-types'; | |
class TimedComponent extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {}; | |
} | |
componentDidMount() { | |
const setState = this.setState.bind(this); | |
this.setState = setState; | |
const { stateDefaults } = this.props; | |
if (stateDefaults !== undefined) { | |
setState(stateDefaults); | |
} | |
const { interval, intervalFn } = this.props; | |
if (interval !== undefined) { | |
if (typeof interval !== 'number') throw Error('interval must be typeof number'); | |
if (typeof intervalFn !== 'function') throw Error('intervalFn must be typeof function'); | |
this.mountedInterval = setInterval(() => intervalFn(setState), interval); | |
intervalFn(setState); | |
} | |
const { timeout, timeoutFn } = this.props; | |
if (timeout !== undefined) { | |
if (typeof timeout !== 'number') throw Error('timeout must be typeof number'); | |
if (typeof timeoutFn !== 'function') throw Error('timeoutFn must be typeof function'); | |
this.mountedTimeout = setTimeout(() => timeoutFn(setState), timeout); | |
} | |
} | |
componentWillUnmount() { | |
if (this.mountedTimeout !== undefined) { | |
clearTimeout(this.mountedTimeout); | |
} | |
if (this.mountedInterval !== undefined) { | |
clearInterval(this.mountedInterval); | |
} | |
} | |
render() { | |
const { childComponent: ChildComponent } = this.props; | |
return <ChildComponent {...this.state} />; | |
} | |
} | |
TimedComponent.propTypes = { | |
stateDefaults: PropTypes.object, | |
interval: PropTypes.number, | |
intervalFn: PropTypes.func, | |
timeout: PropTypes.number, | |
timeoutFn: PropTypes.func, | |
childComponent: PropTypes.func.isRequired, | |
}; | |
TimedComponent.defaultProps = { | |
stateDefaults: undefined, | |
interval: undefined, | |
intervalFn: undefined, | |
timeout: undefined, | |
timeoutFn: undefined, | |
}; | |
export default TimedComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment