#Trying to pause and unpause a youtube video
13 messages · Page 1 of 1 (latest)
I see. Thank you for this!!
Have you tried using ref instead of state
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
after playing around, i gathered that pauseVideo() does work, its just that it is having an error when isPlaying is set to false for some reason
Where is your click handler btw
'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>
@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