0

I am trying to auto close the lightbox, once the video is finished playing.

onEnded attribute worked great 99.99% of time, but sometimes it's not firing callback. So I tried to use onDuration.

Above error occurs in the callback set to onDuration. Console prints duration fine but I am not sure why it can't identify following method and throwing error. this.props.lightBoxHandler(this.props.entry.type);

  renderEntry() {
        if (this.props.entry.type === "photo") {
            this.disableLightbox();
         return  <img alt={Math.random()} src={this.props.entry.entry} onClick={ () => this.props.lightBoxHandler(this.props.entry.type)} />
        } 
        if (this.props.entry.type === "video") {
        return   <ReactPlayer
            url={this.props.entry.entry}
            className='react-player'
            playing={true}
            width='100%'
            height='100%'
            onEnded={() => this.props.lightBoxHandler(this.props.entry.type)}
            onDuration={(duration) => {
                console.log("Duration " + duration);
                setTimeout(function () {
                    this.props.lightBoxHandler(this.props.entry.type);
            }, duration*1000)  }}
            />
        }
    }

    render() {
        let classList = this.props.entry.is === true ? "lightbox-wrapper active" : "lightbox-wrapper";
        return ( 
            <React.Fragment>
                <div className={classList}>
                    {this.renderEntry()}
                </div>
            </React.Fragment>
         );
    }
Ishan Patel
  • 5,571
  • 12
  • 47
  • 68
  • Where is that prop coming from? – Max Jan 23 '19 at 23:42
  • Hi @Max prop is coming from different component. Thing is if I call the same prop for `onEnded`, it works, but when I call it with `onDuration`, it throws error. – Ishan Patel Jan 24 '19 at 01:54

1 Answers1

1

TLDR: Change the function inside your setTimeout to an arrow function and it should work.

The reason this.props.lightBoxHandler is defined in onEnded but not in onDuration is because in onDuration you are calling this.props inside of a function in your setTimeout that is declared with the function keyword, as opposed to an arrow function.

Arrow functions use this from the lexical scope. Functions defined with function have their own this.

See: https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

Max
  • 1,517
  • 9
  • 16