How do I make the video start playing itself when the video is swiped?
When the user just opens the feed feed so that the video starts playing immediately, when there is a swipe to another video, then the new video starts playing, and the old one stops?
Also, the user can pause the video himself when clicking on it
The option that I have now does not work well, autoplay does not occur and when only the 3rd time the video starts, nothing happens with swipes. If you start the video and swap it to another one, the old one will continue to play, and the new one on which the user is located will not play.
export const Feed = () => {
const { data } = useGetVideoQuery();
const [activeVideoIndex, setActiveVideoIndex] = useState(0);
const activateVideo = (index: number) => {
setActiveVideoIndex(index);
};
console.log(data);
return (
<div className={styles.feed}>
{data?.data.map((video, index) => {
return (
<div key={video.video_id} className={styles.video}>
<div className={styles.video_wrapper}>
<Video
video={video}
isActive={activeVideoIndex === index}
onActivate={() => activateVideo(index)}
/>
<Aside video={video} />
</div>
<Footer video={video} />
</div>
);
})}
</div>
);
};
type Props = {
video: DataVideo;
isActive: boolean;
onActivate: () => void;
};
export const Video = ({ video, isActive, onActivate }: Props) => {
const videoRef = useRef<HTMLVideoElement>(null);
const [isPlaying, setPlaying] = useState(isActive);
const handleClick = () => {
const newPlayingState = !isPlaying;
setPlaying(newPlayingState);
if (videoRef.current) {
newPlayingState ? videoRef.current.play() : videoRef.current.pause();
}
};
useEffect(() => {
if (isActive) {
setPlaying(true);
videoRef.current?.play();
} else {
setPlaying(false);
videoRef.current?.pause();
}
}, [isActive]);
useEffect(() => {
if (videoRef.current) {
isPlaying ? videoRef.current.play() : videoRef.current.pause();
}
}, [isPlaying]);
return (
<div
className={classNames(styles.video_item, isPlaying ? styles.playing : '')}
onClick={() => handleClick()}
onMouseEnter={onActivate}
>
<video
ref={videoRef}
className={styles.video}
autoPlay={isActive}
loop={true}
src={video.play}
playsInline={true}
width='100%'
height='auto'
controls={false}
controlsList='nofullscreen nodownload noremoteplayback'
preload='auto'
poster={video.cover}
/>
{!isPlaying && (
<div
className={styles.video_item__controls}
onClick={() => handleClick()}
>
<img
src='/public/controls/play.svg'
alt='pause'
className={styles.control}
/>
</div>
)}
</div>
);
};
I tried to play with states, but nothing works, then one works, then the other falls off