Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

488
Views
Getting Uncaught TypeError: Cannot set properties of null while using useRef

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
    }
    
    getDeviceMedia()
  }, [])

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
    }
  }
  getDeviceMedia();
},[])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!