react-youtube icon indicating copy to clipboard operation
react-youtube copied to clipboard

e.target.playVideo() works intermittently

Open Nefcanto opened this issue 3 years ago • 1 comments

I'm using your library to play YouTube videos. I'm using it inside a next.js app.

Here's my code:


const PlayeYoutube = ({ videoCode }) => {

    const [_window, setWindow] = useState(null)

    const [opts, setOpts] = useState(null)

    useEffect(() => {
        setWindow(window)
        setOpts({
            height: '390',
            width: '640',
            playerVars: {
                origin: window.location.origin
            },
        })
    }, [])

    const handleStateChange = e => {
          var playingInterval = setInterval(() => {
              console.log('trying to play the video ...')
              if (e.target.getPlayerState() === 1) {
                  clearInterval(playingInterval)
              }
              else {
                  e.target.playVideo()
              }
          }, 100)
          window.e = e
    }

    return <div>
        {
            _window && opts && <YouTube
                videoId={videoCode}
                opts={opts}
                onStateChange={e => handleStateChange(e)}
                onEnd={() => onEnd()}
            />
        }
    </div>
}

The problem is that, when I use e.target.playVideo() inside onStateChange, sometimes it works and sometimes it does not work.

I tried to create an interval to check the player state. But when it does not play the video, player state always returns -1. Even when I can clearly see that the video is loaded inside UI and even seek bar starts to buffer.

What could be the problem? How can I debug this or fix this?

Thanks

Nefcanto avatar Mar 25 '22 09:03 Nefcanto

It's properly working for me. The only difference is I don't use window checker to render the component. and Also I've attached onReady event handler that plays the video.

Besuf avatar Sep 10 '22 12:09 Besuf