react-works icon indicating copy to clipboard operation
react-works copied to clipboard

react-interval: enabled ignored when switched with callback

Open antmarot opened this issue 7 years ago • 0 comments

Hi,

I used the component for a very simple task: count x seconds before stopping the interval. Surprisingly, the interval never stopped.

Here a sample code

import ReactInterval from 'react-interval';

class Demo extends Component {
  constructor(props) {
    super(props);
    this.state = { remaining: 5 };
    this.onTick = this.onTick.bind(this);
  }

  onTick() {
    const { remaining } = this.state;
    this.setState({ remaining: remaining - 1 });
  }

  render() {
    const { remaining } = this.state;
    return (
      <div>
        <ReactInterval
          enabled={remaining > 0}
          callback={this.onTick}
        />
        <span>{remaining}</span>
      </div>
    );
  }
}

export default Demo;

I found out that stop() was correctly called when enabled switched from true to false, but start() was then immediately called as well.

The issue is kind of related to the life-cycle of the component. For instance, if I use a setTimeout to delay the state change a bit, everything works. But if the enabled prop is switched to false "during" the callback, start() will be called anyway and the interval will not stop.

The culprit is probably this bit:

  callback = () => {
    if (this.timer) {
      this.props.callback();
      this.start();
    }
  };

It should be easily fixed by checking the enabled prop before calling start().

antmarot avatar Jan 15 '18 17:01 antmarot