TypeError: Cannot read properties of null (reading 'attachShadow')

Viewed 55

I have this code in my vue component and when I build it as web component I got the error TypeError: Cannot read properties of null (reading 'attachShadow') I build the vue component with the following command vue-cli-service build --target wc --name web-stream './src/components/myComponent.vue'

the template section seems like :

<template>
  <div id='stream'>
    <button v-on:click="startStreaming">
    Start Streaming 
    </button> 
 </div>
</template>

inside the section of methods i have:

methods: {
  startStreaming: function(){
        navigator.mediaDevices.getUserMedia({video: true, audio:true}) 
              }).then(function(mediaStream){
                let videoElement = document.createElement('video')
                let shadowElement = document.getElementById('stream')
                shadowElement.attachShadow({ mode: "open" }).appendChild(videoElement)

                videoElement.srcObject = mediaStream
                newVideo.play()
            }).catch(function(error){alert(error)}),                    
    }

i will appreciate any help, any suggestion

1 Answers

In JS, anytime you see TypeError: Cannot read properties of null, this means you are reading a property or calling a function/method from a null (instead of an object).

This is where you need to look into:

let shadowElement = document.getElementById('stream')
shadowElement.attachShadow({ mode: "open" }).appendChild(videoElement)

The problem with this is that there is no guarantee for document.getElementById('stream') to return a dom element or even simply your code run before the element is available.

It could be because of a miss typing, or someone changing/deleting the id attribute in the HTML.

Fix it by an if condition

if (shawdowElement) {
  // your code
} else {
  // report "shadow element" doesn't exist
}

or using Optional chaining (?.)

shadowElement?.attachShadow()

Read more about Optional Chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

That is for fixing the error.

But I believe to make your app run correctly, you need to identify why your document.getElementById('stream') returned null.

Related