-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuse-receive-peer-state.tsx
More file actions
64 lines (52 loc) · 1.93 KB
/
use-receive-peer-state.tsx
File metadata and controls
64 lines (52 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { useEffect, useState } from 'react';
import Peer from 'peerjs';
import { PeerError } from './types';
const useReceivePeerState = <TData extends {}>(
peerBrokerId: string,
opts: { brokerId: string } = { brokerId: '' },
connectionOpts?: Peer.PeerConnectOption
): [TData | undefined, boolean, any, Peer.DataConnection | undefined, Peer | undefined] => {
const [state, setState] = useState<TData | undefined>(undefined);
const [isConnected, setIsConnected] = useState(false);
const [peer, setPeer] = useState<Peer | undefined>(undefined);
const [connection, setConnection] = useState<Peer.DataConnection | undefined>(undefined);
const [brokerId, setBrokerId] = useState(opts.brokerId);
const [error, setError] = useState<PeerError | undefined>(undefined);
useEffect(
() => {
if (!peerBrokerId) {
return;
}
import('peerjs').then(({ default: Peer }) => {
const localPeer = new Peer(opts.brokerId);
setPeer(localPeer);
localPeer.on('open', () => {
if (brokerId !== localPeer.id) {
setBrokerId(localPeer.id);
}
const connection = localPeer.connect(peerBrokerId, connectionOpts);
setConnection(connection);
connection.on('open', () => {
connection.on('data', (receivedData: TData) => {
// We want isConnected and data to be set at the same time.
setState(receivedData);
setIsConnected(true);
});
});
connection.on('close', () => {
setIsConnected(false);
});
connection.on('error', err => setError(err));
});
localPeer.on('error', err => setError(err));
});
return () => {
setIsConnected(false);
peer && peer.destroy();
};
},
[peerBrokerId, opts.brokerId]
);
return [state, isConnected, error, connection, peer];
};
export default useReceivePeerState;