Skip to content

Commit 69e4105

Browse files
committed
improvement: added backward compatibility
Added backward compatibility by implementing the timer as a class component rather than a functional component
1 parent 4017d4f commit 69e4105

File tree

1 file changed

+43
-25
lines changed

1 file changed

+43
-25
lines changed

src/index.js

+43-25
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,52 @@
1-
import { useState, useEffect, useRef } from 'react';
1+
import { Component } from 'react';
22
import PropTypes from 'prop-types';
33

4-
const ReactTimer = ({
5-
children,
6-
start = 0,
7-
end = () => true,
8-
interval = 1000,
9-
onEnd = () => { },
10-
onTick = () => { },
11-
}) => {
12-
const [value, setValue] = useState(start);
13-
const timerRef = useRef();
4+
class ReactTimer extends Component {
5+
constructor(props) {
6+
super(props);
7+
this.state = {
8+
value: props.start || 0,
9+
};
10+
this.timer = null;
11+
}
1412

15-
useEffect(() => {
16-
if (!timerRef.current) {
17-
timerRef.current = setInterval(() => {
18-
setValue((val) => onTick(val));
19-
}, interval);
20-
}
21-
if (end(value)) {
22-
clearInterval(timerRef.current);
23-
onEnd(value);
13+
componentDidMount() {
14+
const {
15+
onTick,
16+
interval,
17+
end,
18+
onEnd,
19+
} = this.props;
20+
this.timer = setInterval(() => {
21+
this.setState(({ value }) => (
22+
{ value: onTick(value) }
23+
), () => {
24+
const { value: currentValue } = this.state;
25+
if (end(currentValue)) {
26+
clearInterval(this.timer);
27+
onEnd(currentValue);
28+
}
29+
});
30+
}, interval);
31+
}
32+
33+
componentWillUnmount() {
34+
if (this.timer) {
35+
clearInterval(this.timer);
2436
}
25-
}, [end, interval, onEnd, onTick, value]);
37+
}
2638

27-
useEffect(() => () => {
28-
clearInterval(timerRef.current);
29-
}, []);
39+
render() {
40+
const { children } = this.props;
41+
const { value } = this.state;
42+
return children(value);
43+
}
44+
}
3045

31-
return children(value);
46+
ReactTimer.defaultProps = {
47+
interval: 1000,
48+
onEnd: () => { },
49+
onTick: () => { },
3250
};
3351

3452
ReactTimer.propTypes = {

0 commit comments

Comments
 (0)