Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

503
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda