Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/use-peer-state.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@ import { PeerError } from './types';
const usePeerState = <TState extends {}>(
initialState: TState,
opts: { brokerId: string } = { brokerId: '' }
): [TState, Function, string, Peer.DataConnection[], any] => {
): [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);
Expand DownExpand Up@@ -36,6 +36,17 @@ const usePeerState = <TState extends {}>(
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;
})
});
});
});

Expand All@@ -55,7 +66,8 @@ const usePeerState = <TState extends {}>(
},
brokerId,
connections,
error,
peer,
error
];
};

Expand Down
11 changes: 7 additions & 4 deletions src/use-receive-peer-state.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,11 +4,13 @@ import { PeerError } from './types';

const useReceivePeerState = <TData extends {}>(
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<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);

Expand All@@ -27,7 +29,8 @@ const useReceivePeerState = <TData extends {}>(
setBrokerId(localPeer.id);
}

const connection = localPeer.connect(peerBrokerId);
const connection = localPeer.connect(peerBrokerId, connectionOpts);
setConnection(connection);

connection.on('open', () => {
connection.on('data', (receivedData: TData) => {
Expand DownExpand Up@@ -55,7 +58,7 @@ const useReceivePeerState = <TData extends {}>(
[peerBrokerId, opts.brokerId]
);

return [state, isConnected, error];
return [state, isConnected, error, connection, peer];
};

export default useReceivePeerState;