Reputation: 25
I'm trying to learn about WebRTC and p2p com with React JS. I just want to see the video of the computer camera on localhost but it gives me this error:
TypeError: undefined is not an object (evaluating 'this.localVideoref')
(anonymous function) — App.js:18
promiseReactionJob
You can see my App.js below:
import React, {Component} from "react";
class App extends Component {
constructor(props){
super(props)
this.localVideoref = React.createRef()
}
render(){
const constraints = { audio: false, video: true }
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
console.log('stream: ' , stream)
this.localVideoref.current.srcObject = stream
})
.catch(function(e) {
console.log('getUserMedia Error: ', e)
});
return (
<div>
<video ref={this.localVideoref} autoPlay></video>
</div>
);
}
}
export default App;
I saw that mediaDevices only works on secure connection, so I installed a new certificate to my localhost and run the project as HTTPS:enable but nothing changed. Using https:localhost is not the answer for me.
Upvotes: 1
Views: 792
Reputation: 156
I'll post this with hooks because it's what I use now.
It's best to move the asynchronous code to an effect (or in your case, probably componentDidMount
) and let the video re-render when the source is available.
This worked for me:
const App = () => {
const localVideoRef = useRef(null);
useEffect(() => {
if (!localVideoRef) return;
const constraints = { audio: false, video: true };
const setSource = async () => {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
localVideoRef.current.srcObject = stream;
};
setSource();
}, [localVideoRef]);
return (
<div>
<video ref={localVideoRef} autoPlay></video>
<div>
)
}
Upvotes: 1