1

I am trying to stream a video, but when i set 'myVideo.current.srcObject = currentStream' as in the code below, I recieve an error 'Cannot set properties of undefined (setting 'srcObject')'

const myVideo = useRef({});  
const userVideo = useRef({});  
const connectionRef = useRef();  
useEffect(() => {  
  navigator.mediaDevices  
    .getUserMedia({ video: true, audio: true })  
    .then((currentStream) => {  
      setStream(currentStream);  
      myVideo.current.srcObject = currentStream;  
    });  
  socket.on("me", (id) => {  
    setMe(id);  
  });socket.on("callUser", ({ from, callerName, signal }) => {  
    setCall({ isReceivedCall: true, from, callerName, signal });  
  });  
}, []);```




  

1 Answers1

2

When using const myVideo = useRef(), the value of myVideo.current may be undefined until the ref has been attached to something.

You may need to check that myVideo.current exists before doing any operations on it.

You could do this with if statements or optional chaining

if

if (myVideo.current) {
  // do something
  myVideo.current.srcObject = currentStream;
}

optional chaining

myVideo.current?.srcObject = currentStream;

Both will only execute once the myVideo.current has a value

Harrison
  • 1,654
  • 6
  • 11
  • 19
  • Yes i tried that code then i executed console.log("Video streaming"), It logged it on the console but the video is not yet streaming – Williams Alex Dec 15 '22 at 09:50
  • You may need to execute your code in a `useEffect` hook, if the `currentStream` value changes. I'm not 100% sure if the stream will play immediately without the [autoplay](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/autoplay) attribute set – Harrison Dec 15 '22 at 10:07