Home > Net >  React - How to go back to default state?
React - How to go back to default state?

Time:12-22

I'm playing a Youtube video. Once something is typed down, the API server would reply back with a URL that is played in the same player as the Youtube's. How can I go back to the YT video once the API's video is over?

The Player video code (Typescript) looks like this, and it is fed by videoUrlProp, a state that handles the URL response from the parent component.

const Player: React.FC<IProps> = ({
  onProgress,
  videoUrlProp,
}:
IProps) => {

// Don't mind this segment.
  const { playerRef, isPlaying } = useStore(
    (state) => ({ playerRef: state.playerRef, isPlaying: state.isPlaying }),
    shallow
  );

  // We check if the source is the original. This is used to resize the player.
  const isOriginalVideo = videoUrlProp.includes("youtube");

  return (
    <div className="player">
      <ReactPlayer
        url={videoUrlProp}
        controls={true}
        onProgress={onProgress}
        width={isOriginalVideo ? "100%" : "70%"}
        height={isOriginalVideo ? "100%" : "100%"}
        className="react-player"
        ref={playerRef}
        playing={isPlaying}
      />
    </div>
  );
};

export default Player;

I'm using the react-player for the player; and this is how the state was declared in the parent component:

const [videoUrl, setVideoUrl] = useState(
    "https://www.youtube.com/watch?v=something"
  );

Any help is welcomed. Thank you!

*Edit: I'm still kinda new to asking on stackoverflow, please do let me know if I'm missing some data or if I should write things down in a different way! Ty! :)

CodePudding user response:

A state doesn't have a "reset" function. But it's easy to simulate it.

If you setup your state and expose the default/initial value, then you would have something like:

const defaultVideoUrl = "https://www.youtube.com/watch?v=something"

Then in your component somewhere, declare the state:

const [videoUrl, setVideoUrl] = useState(defaultVideoUrl);

Then you set back to that default value when the video ends, which according to the docs is by using the onEnded prop:

<ReactPlayer
  ...otherProps
  onEnded={() => setVideoUrl(defaultVideoUrl)}
/>

CodePudding user response:

You can pass a function props to your child component, call it when the video is over with a useEffect to trigger a reset in your parent component.

useEffect(()=> { 
   if (isVideoFinished) props.reset(true)
}, [isVideoFinished])

and in your parent component simply do

const reset = (shouldReset) => {
  if (shouldReset) {
    setVideoUrl('reset to whatever you want')
  }
}
  • Related