This is based on the answer given here:
I'm having trouble resetting a setInterval.
As of now the following works. I have a prop called mediaList
which contains an object array of images. When changeActiveMedia
is called, the object position is moved to the next one in the list.
class MyComponent 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>
)
}
}
My problem arises here.
I have logic that can change the number of objects in the list, mediaList
.
This becomes a problem because since the interval only updates once every 5000 seconds, if the nextMediaIndex
within that time is 2, and then I all of a sudden update the mediaList to have only 1 item, I run into an error since mediaList[2] would not exist.
So my question is, is there a way to RESET and CLEAR the setInterval whenever this.props.mediaList
is updated?