-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathuse-peer-state.tsx
More file actions
74 lines (64 loc) · 2.22 KB
/
use-peer-state.tsx
File metadata and controls
74 lines (64 loc) · 2.22 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
65
66
67
68
69
70
71
72
73
74
import { useEffect, useState, useRef } from 'react';
import Peer from 'peerjs';
import { PeerError } from './types';
const usePeerState = <TState extends {}>(
initialState: TState,
opts: { brokerId: string } = { brokerId: '' }
): [TState, Function, string, Peer.DataConnection[], Peer | undefined, any] => {
const [connections, setConnections] = useState<Peer.DataConnection[]>([]);
const [state, setState] = useState<TState>(initialState);
const [error, setError] = useState<PeerError | undefined>(undefined);
// We useRef to get around useLayoutEffect's closure only having access
// to the initial state since we only re-execute it if brokerId changes.
const stateRef = useRef<TState>(initialState);
const [peer, setPeer] = useState<Peer | undefined>(undefined);
const [brokerId, setBrokerId] = useState(opts.brokerId);
useEffect(
() => {
import('peerjs').then(({ default: Peer }) => {
const localPeer = new Peer(opts.brokerId);
setPeer(localPeer);
localPeer.on('open', () => {
if (brokerId !== localPeer.id) {
setBrokerId(localPeer.id);
}
});
localPeer.on('error', err => setError(err));
localPeer.on('connection', conn => {
setConnections(prevState => [...prevState, conn]);
// We want to immediately send the newly connected peer the current data.
conn.on('open', () => {
conn.send(stateRef.current);
});
conn.on('close', () => {
setConnections(prevState => {
var indexOfClosedConnection = prevState.findIndex(value => value.peer === conn.peer);
if (indexOfClosedConnection !== -1) {
prevState.splice(indexOfClosedConnection, 1);
return [...prevState];
}
return prevState;
})
});
});
});
return () => {
peer && peer.destroy();
};
},
[opts.brokerId]
);
return [
state,
(newState: TState) => {
setState(newState);
stateRef.current = newState;
connections.forEach(conn => conn.send(newState));
},
brokerId,
connections,
peer,
error
];
};
export default usePeerState;