Unmounting a Component with a SetInterval in React
Asked Answered
V

1

9

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?

Voodooism answered 30/3, 2017 at 0:26 Comment(1)
setInterval returns an id which you later pass ti clearInterval on unmount.Aerophobia
A
20

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);

Assessor answered 30/3, 2017 at 2:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.