Search code examples
javascriptreactjsvideo.jsaws-amplify

In react.js how can you asynchronously assign source attribute for video.js object


My knowledge gap is understanding how to use async properly to have the correct value for attribute 'src' of object 'const videoJsOptions'.

import React, { useEffect, useState } from 'react';
import VideoPlayer from "./VideoPlayer";
import Amplify, { Storage } from 'aws-amplify';

function VideoPlayerPage () {
    const [state, setState] = React.useState({ vidSrc: "" })

    useEffect(() => {
        async function getURI() {
        try {
            const value = await Storage.get("andy_2020_something_description.mp4");
                    console.log(value);
            setState({ vidSrc: value });
        } catch (error) {
      console.log(error);
          } 
        }
        getURI();
    }, [] );

    const videoJsOptions = {
        autoplay: true,
        controls: true,
        sources: [{
// If I replace the reference to state on the line below with a string of the URL then the video.js player will work fine.
            src: state.vidSrc,
            type: 'video/mp4'
        }]
    }

    return (
        <div>
            <h1> value of state: { state.vidSrc } </h1>
            <VideoPlayer {...videoJsOptions} />
        </div>
    )
}

export default VideoPlayerPage

So what is rendered/displayed on the page by the line:

value of state: { state.vidSrc }

is a perfectly valid URL. If I hardcode this URL as a string to replace the variable on line:

src: state.vidSrc, then the video.js player works fine.

I'm thinking that 'const videoJsOptions' may be passed to the VideoPlayer Component too early, but I cannot figure out how to fix this, that is, have it wait until later such as when the line:

value of state: { state.vidSrc }

is displayed.

Ideas to debug further are greatly appreciated.


Solution

  • why dont you do a conditional rendering,

     { state.vidSrc && <VideoPlayer {...videoJsOptions} /> } 
    

    this would ensure that the player is only rendered after the correct value is available