ES6 Plato on Github
Report Home
Summary Display
containers/Logbook/PeriodicRefresher.js
Maintainability
77.02
Lines of code
64
Difficulty
19.93
Estimated Errors
0.46
Function weight
By Complexity
By SLOC
import React from 'react'; import PropTypes from 'prop-types'; /* React component which can trigger a call periodically and pass the callback result to its child */ class PeriodicRefresher extends React.Component { constructor(props) { super(props); this.state = { data: this.props.initialValue }; this.intervalId = null; this.setRepetition = this.setRepetition.bind(this); this.onSuccess = this.onSuccess.bind(this); this.onFailure = this.onFailure.bind(this); if (this.props.isEnabled === true) { this.setRepetition() }; } render() { return React.cloneElement(this.props.children, { periodicdata: this.state.data }); } componentDidUpdate() { if (this.props.isEnabled !== undefined) { if (this.props.isEnabled === true) { this.setRepetition() } else { clearInterval(this.intervalId); this.intervalId = null; } } } componentWillUnmount() { clearInterval(this.intervalId); } onSuccess(data) { this.setState({ data: data }) this.props.onCallbackSuccess(data) } onFailure() { console.log('Periodic callback failed') } setRepetition() { if (this.intervalId === null) { this.intervalId = setInterval(() => { return this.props.periodicCallback(this.onSuccess, this.onFailure) }, this.props.intervalInMilliSeconds); } } } PeriodicRefresher.propTypes = { /* Initial value returned in periodicData property to PeriodicRefresher's child. Can be anything. It must be a similar object to what periodic data will return in normal operation */ initialValue: PropTypes.any, /* Timer interval between 2 calls to the callback periodicCallback */ intervalInMilliSeconds: PropTypes.number.isRequired, /* whether the period call is enabled or disabled */ isEnabled: PropTypes.bool, /* callback function which will be triggered periodically */ periodicCallback: PropTypes.func.isRequired } export default PeriodicRefresher;