Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

490
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda