react-peer-data icon indicating copy to clipboard operation
react-peer-data copied to clipboard

How work with customChannel?

Open jarikus18 opened this issue 5 years ago • 1 comments

jarikus18 avatar Apr 21 '20 10:04 jarikus18

Hi @jarukus, sorry for the delay but I just noticed you issue. Below simple example, please let me know if you have more questions.

As shown in basic example https://github.com/vardius/react-peer-data#examples

  1. Use PeerDataProvider to instantiate and pass peerData object down the component tree
  2. Use hook
  3. Connect to room and send some data as follow
  • send to single participant only participant.send('Hi mate! this is private message.');
  • send to every participant in the room room.send('Some message, can be anything, object etc.');

Simple example, probably could be improved. It is draft only, you have to make it work yourself. But I hope you get the idea.

import React, { useEffect } from 'react';
import { usePeerData } from 'react-peer-data';

function App() {
  const peerData = usePeerData();
  const room = peerData.connect('my-room);

  useEffect(() => {
      room
        .on("participant", participant => {
            participant
                .on("disconnected", () => { console.log('disconnected', participant.id); })
                .on("track", event => { console.log('stream', participant.id, event.streams[0]); })
                .on("message", payload => { console.log(participant.id, payload); })
                .on("error", event => {
                    console.error('peer', participant.id, event);
                    participant.renegotiate();
                });

                // @TODO: store participants in global context or global state ?
                // send only to given participant
                participant.send('Hi mate! this is private message.');
        })
        .on("error", event => { console.error('room', name, event); });


      return () => room.disconnect()
  }, [room]);

//payload object can be everything
const payload = {msg: "Hi there!", date: now()};
//send to everybody in room
room.send(payload);

  return null; // @TODO: render participants
}

export default App;

vardius avatar Apr 26 '20 00:04 vardius