0

I am trying to capture events from an html <video/> tag. I have set a ref to it, and using a useEffect am trying to capture the events. However, i beleive I am not handling the ref correctly and am not capturing any of the events. Can someone spot my error?

  const elementRef = useRef(null);
  function handleEvent(event) {
    console.log(`${event.type}\n`);
  }
  useEffect(() => {
    return () => {
      elementRef.addEventListener('loadstart', handleEvent);
      elementRef.addEventListener('progress', handleEvent);
      elementRef.addEventListener('canplay', handleEvent);
      elementRef.addEventListener('canplaythrough', handleEvent);
      elementRef.addEventListener('ended', handleEvent);
      elementRef.addEventListener('pause', handleEvent);
      elementRef.addEventListener('play', handleEvent);
      elementRef.addEventListener('playing', handleEvent);
      elementRef.addEventListener('ratechange', handleEvent);
      elementRef.addEventListener('seeking', handleEvent);
      elementRef.addEventListener('stalled', handleEvent);
    };
  }, [elementRef]);

in my return i have <video controls src={FirstVid} poster={Poster} width="620" ref={(el) => (elementRef.current = el)}/>

1 Answer 1

1

Use the return of useEffect only for cleanup (removeEventListeners). Add listeners before the return.

Edit: I never heard of using a function as the value of the ref prop

<video controls src={FirstVid} poster={Poster} width="620" ref={elementRef}/>

Then

elementRef.current.addEventListener('loadstart', handleEvent);

But I have not read all the docs so no guarantees...

I would try something like the following:

const elementRef = useRef(null);
  function handleEvent(event) {
    // use a switch/case to check for each event
    console.log(`${event.type}\n`);
  }
  useEffect(() => {
      ['loadstart', /* all the other events */].forEach(event => 
        elementRef.current.addEventListener(event, handleEvent);
      )
      return () => {/* remove all event listeners here */}
  }, [elementRef]);
return <video controls src={FirstVid} poster={Poster} width="620" ref={elementRef}/>
Sign up to request clarification or add additional context in comments.

5 Comments

If i pull it out of the effect it returns a "elementref is Not a function" error, as elementref is defined as null right above
Yes I see, worked great. I guess the issuen was with how i set the ref. Thanks for the response. I was struggling
You are very welcome. 1 final edit. I switched my code sample to use an Array of events to make the sample more DRY
I also suggested you use a switch in the handler to define specific behavior for each event
Thanks @Abraham Labkovsky, I will implement a switch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.