Trying to sync the react players outside of home component using cleanup function but it is not working

36 Views Asked by At
import { Swiper, SwiperSlide } from "swiper/react";

import {
  handleSticky,
  setIsPlaying,
  setIsStarted,
  setTimeStamp,
  videoHandle,
} from "@/redux/slices/videoSlice";
import { RootState } from "@/redux/store";
import { getEventStreamAll } from "@/services/events";
import { Box, Text } from "@chakra-ui/react";

import { useDispatch, useSelector } from "react-redux";
import NextSwiperButton from "../../Common/NextSwiperButton";
import { useQuery } from "react-query";

import LoadingSkeleton from "../../Common/LoadingSkeleton";
import ReactPlayer from "react-player";
import EventPlaceHolder from "./EventPlaceHolder";

const OnGoingEventList = () => {
  const [swiper, setSwiper] = useState<any>(null);
  const parentRef = useRef<HTMLDivElement>(null);
  const playerRef = useRef<ReactPlayer>(null);

  const { data, isLoading } = useQuery("eventStreamAll", getEventStreamAll);
  const dispatch = useDispatch();

  const { isSticky, videoId, videoUrl, timeStampSec, isStarted } = useSelector(
    (state: RootState) => state.video
  );

  const handleYoutube = (event: any) => {
    const payload = {
      videoId: event.streamId,
      videoUrl:
        event.streamLink || "https://www.youtube.com/watch?v=ku5VKha1VB8",
    };
    dispatch(videoHandle(payload));
    dispatch(setIsStarted(true));
    dispatch(setIsPlaying(true));
  };

  const dummyData = [
    {
      streamId: 3,
      round: "Final",
      title: "Game 1: PUBG: PUBG",
      streamLink: "https://www.youtube.com/watch?v=BJ3Yv572V1A",
      startDate: "2023-09-17 07:45:00",
    },
    {
      streamId: 4,
      round: "Final",
      title: "Game 1: PUBG: PUBG",
      streamLink: "https://www.youtube.com/watch?v=ku5VKha1VB8",
      startDate: "2023-09-17 07:45:00",
    },
  ];

  const setTime = (timestamp: number) => {
    dispatch(setTimeStamp(timestamp));
  };

  useEffect(() => {
    let localRef: any = null;
    if (playerRef.current) {
      console.log("playerRef.current.getCurrentTime()");
      localRef = playerRef.current;
    }
    return () => {
      console.log("localRef tomde", localRef);
      if (localRef) {
        console.log("localRefdddd", localRef.getCurrentTime()); // here  localRef.getCurrentTime() is always null why?
      }
    };
  }, []);

  useEffect(() => {
    if (playerRef) {
      setTime(playerRef.current?.getCurrentTime() || 0);
    }
  }, [playerRef, isSticky]);

  useEffect(() => {
    if (playerRef.current) {
      playerRef.current.seekTo(timeStampSec);
    }
  }, [playerRef, timeStampSec, window.location.pathname]);

  return (
    <Box mt={8} mb={55} color="white" position="relative" id="top">
      <Text variant="heading2">Ongoing Events</Text>
      <Box mt={8}>
        <Swiper
          spaceBetween={32}
          slidesPerView={2}
          onSwiper={setSwiper}
          loop={false}
        >
          {dummyData?.map((videoItem: any) => (
            <SwiperSlide key={videoItem?.streamId}>
              <Box
                onClick={() => handleYoutube(videoItem)}
              >
                {videoId === videoItem?.streamId ? (
                  <ReactPlayer
                    url={videoUrl}
                    className="react-player-ongoing"
                    controls={true}
                    loop={false}
                    playing={!isSticky}
                    id="video-player"
                    ref={playerRef}
                    onPlay={() => dispatch(setIsPlaying(true))}
                    onPause={() => dispatch(setIsPlaying(false))}
                  />
                ) : (
                  <>
                    {isLoading ? (
                      <LoadingSkeleton h={{ base: 240, xl: 300 }} count={9} />
                    ) : (
                      <EventPlaceHolder videoItem={videoItem} />
                    )}
                  </>
                )}
              </Box>
            </SwiperSlide>
          ))}
        </Swiper>
      </Box>
      <Box ref={parentRef} />
    </Box>
  );
};

export default OnGoingEventList;

I looked up other questions on how can I save a ref before leaving the page so I can access it in cleanup function. I am trying to sync the time of react players that are in homepage and the one that appears when I leave the homepage. Here I am using playerRef.current.getCurrentTime() to sync. When navigating to another page, for sure, this code doesn't execute since it is homepage code. So what I am trying to do is when user leaves, I am trying to get that ref currentTime in cleanup function but it is always null. Maybe the ref is resetting or ? Don't know if I am doing something wrong or there's a better way to do this?

0

There are 0 best solutions below