I'm trying to unmount a component with a setInterval.
This is based on the answer here:
Component:
class ImageSlider extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activeMediaIndex: 0 };
  }
  componentDidMount() {
    setInterval(this.changeActiveMedia.bind(this), 5000);
  }
  changeActiveMedia() {
    const mediaListLength = this.props.mediaList.length;
    let nextMediaIndex = this.state.activeMediaIndex + 1;
    if(nextMediaIndex >= mediaListLength) {
      nextMediaIndex = 0;
    }
    this.setState({ activeMediaIndex:nextMediaIndex });
  }
  renderSlideshow(){
    const singlePhoto = this.props.mediaList[this.state.activeMediaIndex];
      return(
        <div>
          <img src={singlePhoto.url} />
        </div>
      );
    }
  render(){   
    return(
      <div>
          {this.renderSlideshow()}
      </div>
    )
  }
}
Right now, when I go to another page, I get this error:
Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component
So I added something like this:
   componentWillUnmount(){
    clearInterval(this.interval);
  }
I've also tried:
   componentWillUnmount(){
    clearInterval(this.changeActiveMedia);
  }
But I'm still getting the above error every 5 seconds. Is there a proper way to clear the interval?
setInterval returns an in interval Id that you can use in clearInterval.
More info on setInterval
Something like this should work:
this.myInterval = setInterval(this.changeActiveMedia.bind(this), 5000)
then in componentWillUnmount:
clearInterval(this.myInterval);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With