skip to Main Content

I tried to build a video chat application using React and peerjs. and below is pieces of code that handles it.


const randomPeerId = uuidv4();
const peer = new Peer(randomPeerId);

export function VideoCall() {
  const [peerId, setPeerId] = useState("");

  useEffect(()=>{
    if(!peer) console.log(`No peer detected`);
    console.log('peer exist: ', peer.id);

    peer.on('connection',(conn)=>{
      console.log(`got a connection`);
    })
  },[])


  const connect = (e: any) => {
    e.preventDefault();

    const connection = peer.connect(peerId);
    connection.send('Hi')
  };

  return (
    <div id="video">
      {randomPeerId}
      <h1>Video Call</h1>
      <div>
        <form onSubmit={connect}>
          <input
            type="text"
            id="recepientId"
            placeholder="Enter Peer ID to connect"
            onChange={(e) => setPeerId(e.target.value)}
          />
          <button>Connect</button>
        </form>
      </div>
    </div>
  );
}

Here even though I click connect once. we can see that on the other side its console.log() twice. the same happened when I created the Peer objected inside the function. so, because its getting created twice I have to keep creating of peer object outside the function. (iam an aboslute beginner in react)

enter image description here

2

Answers


  1. That’s because during development with StrictMode React mounts, and immediately unmounts and then mount your component to help catch bugs (among others).

    In your case, for example, you should clean up the connection, like so:

    useEffect(()=>{
      if(!peer) console.log(`No peer detected`);
      console.log('peer exist: ', peer.id);
    
      peer.on('connection',(conn)=>{
        console.log(`got a connection`);
      })
      // This function will get called when the component gets unmounted:
      return () => {
         peer.destroy()
      }
    },[])
    

    To know more about this behaviour, checkout this thread.

    Login or Signup to reply.
  2. You can disable react strict mode, in your app file you should find a tag ReactSrict mode just remove it, but this only happens in dev

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search