Skip to content

add eventlisterner in useEffect in CustomPlyrInstance not working with empty dependency array #732

Closed
@bradrice

Description

@bradrice

If I leave off the dependency array, the eventlisteners get attached, but mulitple times due to rerenders of the AudioPlayer component I have created. I would like to prevent adding additional event listeners.

Here is my code in the useEffect

React.useEffect(() => {
      /**
       * Fool react for using forward ref as normal ref
       * NOTE: in a case you don't need the forward mechanism and handle everything via props
       * you can create the ref inside the component by yourself
       */
      const { current } = ref as React.MutableRefObject<APITypes>;
      if (current.plyr.source === null) return;

      const api = current as { plyr: PlyrInstance };
      api.plyr.on("ready", onReady);
      api.plyr.on("canplay", onCanPlay);
      api.plyr.on("ended", onEnded);
      eventBus.on("imagesLoaded", () => {
        console.log("images have loaded, time to play");
        // api.plyr.play();
      });

      return () => {
        api.plyr.off("ended", onEnded);
        api.plyr.off("ready", onReady);
        api.plyr.off("canplay", onCanPlay);
      };
    }, []);

Why can't I pass an empty array to minimize the calls to add the event listeners?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions