I'm currently working on a personal project to embed a YouTube video and render the current state of the video player on the page using a YouTube API call to getPlayerState(). Here's the code I have right now, and my logic was that I could update playerState depending on what the getPlayerState function returns.
Here's the API function: https://developers.google.com/youtube/iframe_api_reference#Playback_status.
However, the playerState that comes up on the page never updates. It just always stays at Unstarted, which is what I initialized to, even after the video starts playing.
Would someone mind explaining what error I might be encountering, and a possible fix? I've looked at this for a long time and can't quite figure out why this is. Thank you so much!
import React from 'react';import ReactPlayer from "react-player"class VideoPlayer extends React.Component { constructor(props) { super(props); this.state = { playerState: "Unstarted", youtubeIsClicked: false, }; } handleVideoPlayerState = (e) => { this.currentVideoPlayerState(e); } currentVideoPlayerState = async (e) => { let [currentPlayerState] = await Promise.all([ e.target.getPlayerState() ]); switch (currentPlayerState) { case -1: console.log('onPlayerStateChange', currentPlayerState); this.setState({ playerState: "Unstarted" }) break; case 0: console.log('onPlayerStateChange', currentPlayerState); this.setState({ playerState: "Ended" }) break; case 1: console.log('onPlayerStateChange', currentPlayerState); this.setState({ playerState: "Playing" }) break; case 2: console.log('onPlayerStateChange', currentPlayerState); this.setState({ playerState: "Paused" }) break; case 3: console.log('onPlayerStateChange', currentPlayerState); this.setState({ playerState: "Buffering" }) break; case 5: console.log('onPlayerStateChange', currentPlayerState); this.setState({ playerState: "Video cued" }) break; } } handleYouTubeClick = () => { this.setState({ youtubeIsClicked: true, }); } render() { return (<div style={{ width: "80%", margin: "0 auto" }}><h1>Video Player</h1><button onClick={this.handleYouTubeClick}>Youtube</button> {this.state.youtubeIsClicked && (<div><ReactPlayer url="https://youtu.be/2XsP4I9ds4c" playerState={this.state.playerState} onPlayerStateChange={this.handleVideoPlayerState} /><p>Playback State: {this.state.playerState}</p></div> )}</div> ); }}export default YouTubePlayer