webcam not opening in webrtc with react.js - reactjs

import React from 'react';
class Test extends React.Component {
constructor(props){
super(props);
this.status = {
}
}
componentDidMount(){
const pc = new RTCPeerConnection();
document.getElementById("call").onclick = async () => {
const stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
document.getElementById("video").srcObject = stream;
for (const track of stream.getTracks()) {
pc.addTrack(track, stream);
}
};
pc.ontrack = ({streams}) => document.getElementById("video").srcObject = streams[0];
pc.oniceconnectionstatechange = () => console.log(pc.iceConnectionState);
pc.onicecandidate = ({candidate}) => sc.send({candidate});
pc.onnegotiationneeded = async () => {
await pc.setLocalDescription(await pc.createOffer());
sc.send({sdp: pc.localDescription});
}
const sc = new window.localSocket(); // localStorage signaling hack
sc.onmessage = async ({data: {sdp, candidate}}) => {
if (sdp) {
await pc.setRemoteDescription(sdp);
if (sdp.type == "offer") {
await pc.setLocalDescription(await pc.createAnswer());
sc.send({sdp: pc.localDescription});
}
} else if (candidate) await pc.addIceCandidate(candidate);
}
}
render(){
return (
<div>
<video id="video" height="120" width="160" autoplay>
</video>
<br/>
<button id="call">Call!</button>
<br/>
<div id="div"></div>
</div>
)
}
}
export default Test;
Here is my code to open webcam.
I am following https://jsfiddle.net/jib1/2yLakm60 link an doing in react.js
https://jsfiddle.net/jib1/2yLakm60
But, my code is not working.
Webcam light is coming but camera is not showing.
Please take a look hOw can i solve this.

Related

react twilio video: first joiner screen black on participant join

i have made a twillio video app.i can show local video on Laptop website but when i join from another chrome tab or mobile phone chrome browser the video on laptop goes black and only one video is showing whereas both videos should show properly.i am following this tutorial
https://www.twilio.com/blog/build-a-custom-video-chat-app-with-react-and-twilio-programmable-video
here is my code
App.js
import './App.scss';
import React, {Component} from 'react';
import Room from './Components/Room';
const { connect } = require('twilio-video');
const Token = {"identity":"Jose Corkery","token":"...sioAMt4..."}
class App extends Component {
constructor(props) {
super(props)
this.state = {
identity: '',
room: null
}
this.inputRef = React.createRef();
this.joinRoom = this.joinRoom.bind(this);
this.returnToLobby = this.returnToLobby.bind(this);
this.updateIdentity = this.updateIdentity.bind(this);
this.removePlaceholderText = this.removePlaceholderText.bind(this)
}
async joinRoom() {
try {
// const response = Token
// const data = await response.json();
const room = await connect(Token.token, {
name: 'cool-room',
audio: true,
video: true
});
// alert(room)
this.setState({ room: room });
} catch(err) {
alert(err);
}
}
updateIdentity(event) {
this.setState({
identity: event.target.value
});
}
returnToLobby() {
this.setState({ room: null });
}
removePlaceholderText() {
this.inputRef.current.placeholder = '';
}
render() {
const disabled = this.state.identity === '' ? true : false;
return (
<div className="app">
{
this.state.room === null
? <div className="lobby">
<input
ref={this.inputRef}
onClick={this.removePlaceholderText}
placeholder="What's your name?"
onChange={this.updateIdentity}
/>
<button disabled = {disabled} onClick={this.joinRoom}>Join Room</button>
</div>
: <Room returnToLobby={this.returnToLobby} room={this.state.room} />
}
</div>
);
}
}
export default App;
Room.jsx
import React, { Component } from 'react';
import Participant from './Participant';
const { connect } = require('twilio-video');
class Room extends Component {
componentDidMount() {
this.props.room.on('participantConnected', participant => this.addParticipant(participant));
this.props.room.on('participantDisconnected', participant => this.removeParticipant(participant));
window.addEventListener("beforeunload", this.leaveRoom);
}
componentWillUnmount() {
this.leaveRoom();
}
addParticipant(participant) {
console.log(`${participant.identity} has joined the room.`);
alert(`+ Participant : ${participant.identity}`)
this.setState({
remoteParticipants: [...this.state.remoteParticipants, participant]
})
}
removeParticipant(participant) {
alert(`Leaving : ${participant.identity}`)
console.log(`${participant.identity} has left the room`);
this.setState({
remoteParticipants: this.state.remoteParticipants.filter(p => p.identity !== participant.identity)
});
}
leaveRoom() {
this.props.room.disconnect();
this.props.returnToLobby();
}
constructor(props) {
super(props)
this.state = {
remoteParticipants: Array.from(this.props.room.participants.values())
}
this.leaveRoom = this.leaveRoom.bind(this);
}
render() {
return (
<div className="room">
<div className="participants">
<Participant
key={this.props.room.localParticipant.identity}
localParticipant="true"
participant={this.props.room.localParticipant} />
{
this.state.remoteParticipants.map(participant =>
<Participant key={participant.identity} participant={participant} />
)
}
</div>
<button id="leaveRoom" onClick={this.leaveRoom}>Leave Room</button>
</div>
);
}
}
export default Room
Participant.jsx
import React, { Component } from 'react';
import Track from './Track';
const { connect } = require('twilio-video');
class Participant extends Component {
componentDidMount() {
if (!this.props.localParticipant) {
this.props.participant.on('trackSubscribed', track => this.addTrack(track));
}
}
constructor(props) {
super(props);
const existingPublications = Array.from(this.props.participant.tracks.values());
const existingTracks = existingPublications.map(publication => publication.track);
const nonNullTracks = existingTracks.filter(track => track !== null)
this.state = {
tracks: nonNullTracks
}
}
addTrack(track) {
this.setState({
tracks: [...this.state.tracks, track]
});
}
render() {
return (
<div className="participant" id={this.props.participant.identity}>
<div className="identity">{this.props.participant.identity}</div>
{
this.state.tracks.map(track =>
<Track key={track} filter={this.state.filter} track={track}/>)
}
</div>
);
}
}
export default Participant
Track.jsx
import React, { Component } from 'react';
class Track extends Component {
componentDidMount() {
if (this.props.track !== null) {
const child = this.props.track.attach();
this.ref.current.classList.add(this.props.track.kind);
this.ref.current.appendChild(child)
}
}
constructor(props) {
super(props)
this.ref = React.createRef();
}
render() {
return (
<div className="track" ref={this.ref}>
</div>
)
}
}
export default Track
demo:https://android-anime.web.app
i have only two video events onJoin and onLeave do i need additional events ?
what is the solution? if your solution works i will award you best answer.Thanks !!

draft.js - retrieve formatted text from db

My draft.js <TextEditor /> populates body with the text e.g: '{"blocks":[{"key":"3mont","text":"lorem ipsum","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}}' and persists it to the db after using convertToRaw().
In Post.js, I want to retrieve and display the formatted text from the db.
I've read that in order to do this, I must use convertToRaw() and then convertFromRaw() when retrieving it from the db but I'm having the same problems as this (I'm receiving the cors error and Unexpected token u in JSON at position 0) whenever I use convertFromRaw() and try to retrieve the formatted text from the db.
I've set up my server to support cors so why am I receiving the cors error? Is it because I am trying to parse an invalid response into JSON?
How can I get the formatted text from the db in Post.js?
Any help would be really appreciated!
GitHub
CreatePost.js
class CreatePost extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "",
body: EditorState.createEmpty(),
};
}
changeHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = (e) => {
e.preventDefault();
const {
user: { _id },
} = isAuthenticated();
axios({
url: `${API}/post/new-post/${_id}`,
method: "POST",
data: {
...this.state,
body: JSON.stringify(convertToRaw(this.state.body.getCurrentContent())),
},
})
.then((response) => {
// this.setState({ createdPost: this.state.title });
return response
})
.catch((error) => {
if (!this.state.title || !this.state.body) {
this.setState({
error: "This post must contain a title and a body.",
});
}
console.log(error);
});
};
// Attempt to map through blocks
//getText = () => {
// const {body} = this.state;
//const arr = body.blocks.map(({ text }) => text).join(' ')
// console.log(arr)
//}
render() {
const { title, body } = this.state;
return (
<>
<Navbar />
<Tabs>
<TabList>
<Tab>Draft</Tab>
<Tab>Preview</Tab>
</TabList>
<TabPanel>
<div>
<form onSubmit={this.submitHandler}>
<div>
// title input
</div>
<div>
<TextEditor
onChange={(value) => this.setState({ body: value })}
editorState={body}
/>
</div>
<button type="submit">
Publish
</button>
</form>
</div>
</TabPanel>
<TabPanel>
<div>
<h1>{title}</h1>
// display body text value here too
{this.getText()}
</div>
</TabPanel>
</Tabs>
</>
);
}
}
Post.js (display body text)
const [post, setPost] = useState({});
const [error, setError] = useState(false);
const id = props.match.params.id;
const loadSinglePost = (slug, id) => {
read(slug, id).then((data) => {
if (error) {
console.log(data.error);
setError(data.error);
} else {
setPost(data)
console.log(data);
}
});
};
useEffect(() => {
const slug = props.match.params.slug;
loadSinglePost(slug, id);
}, [props]);
return (
<>
<div>
<h3>{post.title}</h3>
...
// display text value below
<p>{post.body}</p>
</div>
</div>
</>
);
};
TextEditor.js
class TextEditor extends React.Component {
constructor(props) {
super(props);
this.plugins = [addLinkPlugin];
}
toggleBlockType = (blockType) => {
this.props.onChange(RichUtils.toggleBlockType(this.props.editorState, blockType));
};
handleKeyCommand = (command) => {
const newState = RichUtils.handleKeyCommand(
this.props.editorState,
command
);
if (newState) {
this.props.onChange(newState);
return "handled";
}
return "not-handled";
};
onUnderlineClick = () => {
this.props.onChange(
RichUtils.toggleInlineStyle(this.props.editorState, "UNDERLINE")
);
};
onBoldClick = (event) => {
this.props.onChange(RichUtils.toggleInlineStyle(this.props.editorState, "BOLD"));
};
onItalicClick = () => {
this.props.onChange(
RichUtils.toggleInlineStyle(this.props.editorState, "ITALIC")
);
};
onAddLink = () => {
const editorState = this.props.editorState;
const selection = editorState.getSelection();
const link = window.prompt("Paste the link -");
if (!link) {
this.props.onChange(RichUtils.toggleLink(editorState, selection, null));
return "handled";
}
const content = editorState.getCurrentContent();
const contentWithEntity = content.createEntity("LINK", "MUTABLE", {
url: link,
});
const newEditorState = EditorState.push(
editorState,
contentWithEntity,
"create-entity"
);
const entityKey = contentWithEntity.getLastCreatedEntityKey();
this.props.onChange(RichUtils.toggleLink(newEditorState, selection, entityKey));
};
toggleBlockType = (blockType) => {
this.props.onChange(RichUtils.toggleBlockType(this.props.editorState, blockType));
};
render() {
return (
<div>
// formatting buttons
<div>
<Editor
blockStyleFn={getBlockStyle}
editorState={this.props.editorState}
handleKeyCommand={this.handleKeyCommand}
onChange={this.props.onChange}
plugins={this.plugins}
placeholder="Post Content"
/>
</div>
</div>
);
}
}
Apparently draft-js does not have html output function because it's supposed to have no assumption on the output so people can tune their output however they want (see this). This means we'll have to implement it ourselves and if you're looking for just an html or markdown output to preserve in the database, then this mono repo can be of help. I've implemented an example of how to do it in this sandbox. Note that I used dangerouslySetInnerHTML for demonstration which is not optimal. You may want to use sanitization and rich text components to display back the posts. As a matter of fact I'd suggest ditching html and going for markdown instead if possible.

React - error result map is not a function?

Framework: React
Error type: result.map is not a function
I am following the book Road to learn React, I tried the below code with hacker news API it worked well but it is not working with this API. I don't know why I'm getting this error, please help.
Link to my sandbox --> https://codesandbox.io/s/react-setup-forked-q0hti?file=/src/App.js
import React, { Component } from "react";
// API chunks
const PATH_BASE = "https://jsonplaceholder.typicode.com/todos";
const PATH_SEARCH = "/search";
const PARAM_SEARCH = "query=";
const DEFAULT_QUERY = "redux";
//const url = `${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`;
//console.log(url);
class App extends Component {
constructor() {
super();
this.state = {
result: null
};
this.hitStories = this.hitStories.bind(this);
}
// handling the local state value
hitStories(result) {
this.setState({
result
});
}
// lifecycle method
// Note: componenetDidMount runs after the render method
componentDidMount() {
fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${DEFAULT_QUERY}`)
.then((response) => response.json())
.then((json_result) => this.hitStories(json_result))
.catch((error) => error);
}
render() {
console.log(this.state)
const { result } = this.state;
if (!result) {
return null;
}
return (
<div>
<h2>Fetch API in React</h2>
{result.map((
item
) => (
<div>
{item.title}
</div>
))}
</div>
);
}
}
export default App;
.map is used on an array, your result is not an array but an object. Try this:
render() {
const { result } = this.state;
return result ? (
<div>
<h2>Fetch API in React</h2>
{ Object.values(result).map((item) => (
<div>{item.title}</div>
))
}
</div>
): null;
}

Closing webcam without reloading

I'm a a beginner in web development and I’m working on a video chat app built with create-react-app. I’m using recordRTC library for record and stream from users’s webcam and microphone.
When I stop recording, I also would like to close the webcam.
import React, { Component } from "react";
import RecordRTC from "recordrtc";
const captureUserMedia = callback => {
const params = { audio: true, video: true };
navigator.mediaDevices
.getUserMedia(params)
.then(callback)
.catch((error) => {
console.error(JSON.stringify(error));
});
};
export default class Recorder extends Component {
constructor(props) {
super(props);
this.recordVideo = null;
this.videoRef = React.createRef();
}
componentDidMount = () => {
captureUserMedia(stream => (this.videoRef.current.srcObject = stream));
};
startRecord = () => {
captureUserMedia(stream => {
this.recordVideo = RecordRTC(stream, { type: "video" });
this.recordVideo.startRecording();
});
};
stopRecord = () => {
this.recordVideo.stopRecording();
this.videoRef.current.srcObject.getTracks().forEach((track) => {
track.stop();
});
};
render() {
return (
<div>
<video ref={this.videoRef} autoPlay muted />
<div>
<button onClick={this.startRecord}>START</button>
<button onClick={this.stopRecord}>STOP</button>
</div>
</div>
);
}
}
I found here a related post where I found this:
stream.getTracks().forEach((track) => {
track.stop()
})
This stop the stream but the red circle is still present on the navigator tab (chrome) and the webcam's light is still lightning.
How can I do to turn off the webcam ?
The only way i found is to force a reload but I don't really wanna do this ...
If someone have an idea, please let me know.
Thanks for your reply :)
I found what I did wrong !
I called two times getUserMedia() method instead of one only (with captureUserMedia function).
You can try with the code below it will be ok !!!
...
componentDidMount = () => {
captureUserMedia((stream) => {
this.videoRef.current.srcObject = stream;
this.recordVideo = RecordRTC(stream, { type: "video" });
});
};
startRecord = () => {
this.recordVideo.startRecording();
};
stopRecord = () => {
this.recordVideo.stopRecording();
this.videoRef.current.srcObject.getTracks().forEach((track) => {
track.stop();
});
};
...

Why preload image don't work?

I wrote a component for preload images. Every image have got a lite version (prop previewUrl) and normal version (prop src)
It seems, everything should be ok, but it's not!. Event onload doesn't work. GET request doesn't happend. I break my mind and don't know where the misstake.
Here is a codepen https://codepen.io/fsdev/pen/bLWgoL of the code below
class Image extends React.Component {
constructor(props){
super(props);
this.state = { src: null };
this.preloadImage = this.preloadImage.bind(this);
}
componentWillMount(){
const { src: bigImage, previewUrl } = this.props;
this.setState({src: previewUrl});
this.preloadImage(bigImage)
.then(() => {
console.log("Loaded");
this.setState({src: bigImage});
})
.catch(e => console.error(e.message))
}
preloadImage(url){
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = resolve;
image.onerror = reject;
image.src = url;
})
}
render(){
const { src } = this.state;
const { previewUrl, ...rest } = this.props;
return(
<img {...rest} src={src} />
)
}
}
class App extends React.Component {
render(){
return(
<Image src="http://res.cloudinary.com/playhs/image/upload/v1518304840/bsyjqxahzr8bmaxuvj04.png"
previewUrl="http://res.cloudinary.com/playhs/image/upload/q_30/v1518304850/ztpj7gnqazk6ng2tzamk.jpg"
/>
)
}
}
ReactDOM.render(
<App/>, document.body
)
Thank you
I'am stupid
My React Component called as Image
and here
const image = new Image();
I call here my own Component :) lol

Resources