diff --git a/src/use-peer-state.tsx b/src/use-peer-state.tsx index 7cdb0d9..908e7f0 100644 --- a/src/use-peer-state.tsx +++ b/src/use-peer-state.tsx @@ -5,7 +5,7 @@ import { PeerError } from './types'; const usePeerState = ( initialState: TState, opts: { brokerId: string } = { brokerId: '' } -): [TState, Function, string, Peer.DataConnection[], any] => { +): [TState, Function, string, Peer.DataConnection[], Peer | undefined, any] => { const [connections, setConnections] = useState([]); const [state, setState] = useState(initialState); const [error, setError] = useState(undefined); @@ -36,6 +36,17 @@ const usePeerState = ( 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; + }) + }); }); }); @@ -55,7 +66,8 @@ const usePeerState = ( }, brokerId, connections, - error, + peer, + error ]; }; diff --git a/src/use-receive-peer-state.tsx b/src/use-receive-peer-state.tsx index 1843266..fdb3fb0 100644 --- a/src/use-receive-peer-state.tsx +++ b/src/use-receive-peer-state.tsx @@ -4,11 +4,13 @@ import { PeerError } from './types'; const useReceivePeerState = ( peerBrokerId: string, - opts: { brokerId: string } = { brokerId: '' } -): [TData | undefined, boolean, any] => { + opts: { brokerId: string } = { brokerId: '' }, + connectionOpts?: Peer.PeerConnectOption +): [TData | undefined, boolean, any, Peer.DataConnection | undefined, Peer | undefined] => { const [state, setState] = useState(undefined); const [isConnected, setIsConnected] = useState(false); const [peer, setPeer] = useState(undefined); + const [connection, setConnection] = useState(undefined); const [brokerId, setBrokerId] = useState(opts.brokerId); const [error, setError] = useState(undefined); @@ -27,7 +29,8 @@ const useReceivePeerState = ( setBrokerId(localPeer.id); } - const connection = localPeer.connect(peerBrokerId); + const connection = localPeer.connect(peerBrokerId, connectionOpts); + setConnection(connection); connection.on('open', () => { connection.on('data', (receivedData: TData) => { @@ -55,7 +58,7 @@ const useReceivePeerState = ( [peerBrokerId, opts.brokerId] ); - return [state, isConnected, error]; + return [state, isConnected, error, connection, peer]; }; export default useReceivePeerState;