IBM / video-streaming-web-player-api

This is the public Web Player API for controlling embedded players created at video.ibm.com.
Apache License 2.0
5 stars 6 forks source link

Issue loading PlayerAPI on React 16 with Next 9.4 #7

Closed atresca-globant closed 3 years ago

atresca-globant commented 3 years ago

Hello guys,

We are implementing a streaming solution using this player and we are having problems with the PlayerAPI module. We are able to see the streaming(broadcasting with OBS) working on the iframe if we don't import the API module, but once we import it the page breaks.

Do you know if is something related to Next.js ? Or if we are missing something on our side? Thanks in advance.

Using React 16.13.1 Next 9.4.4 ibm-video-streaming-web-player-api 1.2.0 (also tried 1.1.0)

Browser logs image

Console logs image

VSCode warning image

jungdaniel commented 3 years ago

Hi @atresca-globant

You are trying to use this library with server side rendering, right? This lib contains parts that only makes sense in the context of a browser. One thing that could work is to use dynamic import though.

I was thinking of something like this:

import React, { useEffect, useRef, useState } from 'react';

export const IBMVideoStreamingEmbed = ({ src }) => {
  const iframeRef = useRef(null);
  const [playerAPI, setPlayerApi] = useState(null);

  useEffect(async () => {
      const { current: iframe } = iframeRef;
      if (!iframe) {
        return;
      }

      const { default: PlayerAPI } = await import('ibm-video-streaming-web-player-api');
      setPlayerApi(new PlayerAPI(iframe));
  }, [iframeRef]);

  const onPlay = () => {
    if (!playerAPI) {
      return;
    }

    playerAPI.callMethod('play');
  }

  return (
     <div>
       <iframe
          ref={iframeRef}
          src={src}
          // other attributes
       />
       <button onClick={onPlay}>
          Play
        </button>
     </div>
  );
}

Let me know if this helped.

Are you using typescript? Would you benefit from having @types/ibm-video-streaming-web-player-api declarations available?

atresca-globant commented 3 years ago

Hi @jungdaniel, thanks for the answer. We are not using SSR, we have disabled it.

I was able to make it work with your code with some small twerks. 1) The async function inside useEffect needs to be an IIFE 2) setPlayerApi( PlayerAPI(iframe) );

What I noticed that actually does the magic is the dynamic imported module. I don't understand why that's the case since we are not using SSR but if I use the normal import with this code doesn't work.

Regarding your comment about Typescript I think that would be good, we are starting a migration and would be nice to migrate this component as well.

Thanks for providing the solution!