I'd like to use React Hook's useRef
to set the src object of a video stream but the video ref null and I get the error: TypeError: Cannot set property 'srcObject' of null at getMedia. I am using useEffect
to call the function that logs the ref.
The strange part is I see both null
and a value for current. See screenshot of console log:
I have read the docs on useRef and looked at every other post on Stack Overflow and Github but cannot figure this out. The closest post is this one. What am I doing wrong?
Condensed code:
const App = () => {
const webcamRef = useRef(null)
useEffect(() => {
getMedia();
}, [webcamRef])
const getMedia = async () => {
try {
console.log(webcamRef);
let stream = await navigator.mediaDevices.getUserMedia({ video: true });
webcamRef.current.srcObject = stream;
} catch (err) {
console.error(err);
}
};
return <video id='webcam' ref={webcamRef} />
}
Full code: Sandbox: https://codesandbox.io/s/blissful-goldstine-rp9k5