Quantcast
Channel: Active questions tagged youtube-api - Stack Overflow
Viewing all articles
Browse latest Browse all 3831

Youtube iFrame API - React, Player is Undefined

$
0
0

I am currently using the iFrame API from my project and I am trying to have custom volume controls so that the user is able to change the volume outside of the iframe video. I have set up the player, but it is always undefined when it's being called outside an eventHandler.

  const { youtubeDetails, volume } = useContext(GlobalContext);  useYoutube(loadVideo);  let player: any;  function loadVideo() {    (window as any).YT.ready(function () {      player = new window.YT.Player("player", {         events: {           onStateChange: onStateChange         }      });    });  }  useEffect(() => {    console.log(player)  // never defined    changeVolume()       }, [volume]); function onStateChange() {   console.log(player)  // always defined }  function changeVolume() {    player.setVolume(volume * 100);  }

This is because loadVideo() is never called again after the very first rerender. Is there a work around this structure so that the goal functionality is achieved?

The custom useYoutube Hooks is as follows:

import React from "react";export const useYoutube = (callback: any) => {  React.useEffect(() => {    if (!(window as any).YT) {      var tag = document.createElement("script");      tag.src = "https://www.youtube.com/iframe_api";      var firstScriptTag = document.getElementsByTagName("script")[0];      firstScriptTag?.parentNode?.insertBefore(tag, firstScriptTag);      tag.onload = callback;    } else {      callback();    }  }, []);};

Viewing all articles
Browse latest Browse all 3831

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>