Home > Mobile >  Getting Uncaught TypeError: Cannot set properties of null while using useRef
Getting Uncaught TypeError: Cannot set properties of null while using useRef

Time:06-03

I'm building an app that needs to access the user's device camera and display the video on the screen. I'm doing it by using a video HTML Object and assigning the media stream as its srcObject, and it is working as I expected. However, TypeScript is still giving me an error because I'm assigning the srcObject property to a possibly null videoRef.current.

First, I get the media and assign it to the videoRef inside a useEffect, like this:

const Page: React.FC = () => {
  const videoRef = useRef<HTMLVideoElement | null>(null)
  const [mediaStream, setMediaStream] = useState<MediaStream | null>(null)

  useEffect(() => {
    const getDeviceMedia = async () => {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: true
      })

      setMediaStream(stream)
      videoRef.current!.srcObject = stream
    }
  }, [])

Finally, I return the HTML video assigning its ref to the video ref:

return(
  <video ref={videoRef} autoPlay muted /> 
)

The media is displayed on the screen correctly (I can see my camera's video) but TypeScript gives me this error:

Uncaught TypeError: Cannot set properties of null (setting 'srcObject')

Am I doing something wrong here or there's a way to go around this error?

CodePudding user response:

That's a JavaScript error your are getting on execution time. Because when useEffect's callback gets called first time, the JSX may not be rendered yet. Therefore videoRef.current is still null. Try doing so:

useEffect(() => {
  const getDeviceMedia = async () => {
    const stream = await navigator.mediaDevices.getUserMedia({
      video: true
    })
    setMediaStream(stream)
    if(videoRef.current){
      videoRef.current.srcObject = stream
    }
  }
},[])
  • Related