dfranca
dfranca

Reputation: 5322

Javascript Video loadmetadata event not being triggered on React-Redux Application

I have a React-Redux application that reads some metadata from videos.

However the code added to the loadmetadata event is never triggered.

As a workaround I have added a timer to wait 1 second before, which is a pretty bad solution and doesn't work every time.

Another thing is that I couldn't find an elegant way to integrate the video element into Redux code without having to manipulate the DOM.

The code looks like this:

  videoPlayerElement = document.getElementById(`videoplayer-${videoId}`);
  videoPlayerElement.addEventListener('loadedmetadata', function(e) {
      const duration = videoPlayerElement.duration;
      ...
  })

The code inside the listener is never executed. I also have tried different ways to assign the loadmetadata event, i.e: assigning directly to videoPlayerElement.onloadmetadata still not working.

I thought it might be because of the scope of the object, so I changed it to a global just for testing... didn't help.

Any other idea about what might be causing?

If I run a simple example, like this one it works fine.

Upvotes: 8

Views: 5425

Answers (1)

trixn
trixn

Reputation: 16309

In react you should use synthetic events where possible. Example for your use case:

class MediaPlayer extends Component {

    handleMetadata = event => {
        const duration = event.currentTarget.duration;
        // ...
    }

    render() {
        const {src} = this.props;

        return(
            <video src={src} onLoadedMetadata={this.handleMetadata} />
        );
    }
}

Upvotes: 7

Related Questions