#Trying to pause and unpause a youtube video

13 messages · Page 1 of 1 (latest)

icy jacinth
#

this doesn't seem related to next.js, you might want to create an issue in the react-youtube repository

chilly aurora
#

Have you tried using ref instead of state

rough crater
#

Just tried it, still doesn't work sadly :<

#

I think it has something to do when isPlaying is false

useEffect(() => {
    if (player) {
      if (!isPlaying) {
        player.playVideo();
      } 
    }
  }, [isPlaying, player]);

for example this code, this persists the same error.

#

I made sure isPlaying is a boolean and console logging it shows that it is either true or false when clicking the pause/play button

rough crater
chilly aurora
#

Where is your click handler btw

rough crater
#
'use client'
import Form from "./components/Form"
import Video from "./components/Video"
import { useState, useEffect } from "react"

const HomePage = () => {
  // Youtube URL
  const { inputURL, videoId, handleChange } = useSavedInputURL();
  const { isPlaying, handlePlay } = usePlayVideo();

  return (
    <>
      <Video videoId={videoId} isPlaying={isPlaying}/>
      <Form 
        inputURL={inputURL} handleChange={handleChange}
        isPlaying={isPlaying} handlePlay={handlePlay}
      />
    </>
  )
}

const useSavedInputURL = () => {
  const [inputURL, setinputURL] = useState('');
  const [videoId, setVideoId] = useState('');

  useEffect(() => {
    const savedinputURL = localStorage.getItem('inputURL');
    
    if (savedinputURL) {
      setinputURL(savedinputURL);
      setVideoId(savedinputURL.split('v=')[1]);
    }
  }, []);

  const handleChange = (e) => {
    const newValue = e.target.value;
    setinputURL(newValue);
    setVideoId(newValue.split('v=')[1]);
    
    localStorage.setItem('inputURL', newValue);
  }

  return { inputURL, videoId, handleChange };
};

const usePlayVideo = () => {
  const [isPlaying, setIsPlaying] = useState(false);

  const handlePlay = (e) => { 
    if (isPlaying) 
      setIsPlaying(false);
    else 
      setIsPlaying(true);
  };

  return { isPlaying, handlePlay };
};

export default HomePage

Here is my root component

#

And my form component with the pause/play button

<div className="form-group">
            <div className="form-row">
                <button onClick={handlePlay}>
                    {isPlaying ? 'Pause' : 'Play'}
                </button>
                <button>Share</button>
            </div>
        </div>
chilly aurora
#

@rough crater, from what I observed, the player object has a h property which is the html element where the video is rendered. And since it takes time for it to be mounted, in the beginning it null, even though the player itself is truthy. You can try changing the check in the useEffect from if (player) to if (player?.h), I think that should work

rough crater
#

holy. you're right. it did work.

#

Thank you so much! I really appreciate it!