**PROBLEM: **
I am trying to take user media once the user clicks on the button, ' enter the room ', and after that, his video (user media ) will be shown,
but when I click on the button place for user media video is occupied and the button gets shifted but no video appears and when I click again, then only the video is shown
import React, { useRef, useState } from 'react'
import styles from './userVideo.module.css'
function UserVideo() {
const video = useRef();
const [stream, setStream] = useState()
const constraints = {
audio: true,
video: {
width: 500,
height: 300
}
}
const getUserMedia = () => {
alert(" getUser Media is called ")
navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then((stream) => {
setStream(stream)
video.current.srcObject = stream
})
}
return (
<div className={styles.userVideoOuterContainer} >
<button onClick={getUserMedia} className={styles.enterRoomButton}>
Enter Room
</button>
{stream && <video muted ref={video} autoPlay style={{ width: "300px" }} />}
</div>
)
}
export default UserVideo
The video be rendered before ref video.current set stream so the first time click to button video.current.srcObject = stream not work. You try let
video.current.srcObject = stream to useEffect has stream is dependencies like below code. Option 1:
const getUserMedia = () => {
navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then((stream) => {
setStream(stream)
})
}
useEffect(() => {
if(video.current){
video.current.srcObject = stream
}
}, [stream])
Option 2: You can let the condition to render video to CSS
<video muted ref={video} autoPlay style={{ width: "300px", display: display: stream ? "block" : "none" }} />