Skip to content
Advertisement

URL.createObjectURL wouldn’t work asynchronously (React)

URL.createObjectUrl wouldn’t work when I re-upload another file after uploading at the first time. videoFile is updated but it doesn’t generate object url…

const [videoFile, setVideoFile] = useState<File>()

const uploadVideo = (selectorFiles: FileList | null) => {
  if(selectorFiles) {
    setVideoFile(selectorFiles[0])
  }
}

return (
  <>
    <video controls>
      <source src={URL.createObjectURL(videoFile)} />
    </video>
    <input type="file" onChange={(e) => uploadVideo(e.target.files)} />
  </>
)

Advertisement

Answer

It works. Just render the video element when file exists.

Refer to the working example on Codesandbox.

import { useState } from "react";

export default function App() {
  const [videoFile, setVideoFile] = useState();

  const uploadVideo = (selectorFiles) => {
    if (selectorFiles) {
      setVideoFile(selectorFiles[0]);
    }
  };

  return (
    <>
      {videoFile && (
        <video controls>
          <source src={URL.createObjectURL(videoFile)} />
        </video>
      )}
      <input type="file" onChange={(e) => uploadVideo(e.target.files)} />
    </>
  );
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement