Created
August 29, 2020 21:47
-
-
Save yojona/f39823d0c6f0718cf20a5e02bf35207e to your computer and use it in GitHub Desktop.
usePeerData - PeerJS for data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect, useCallback } from 'react'; | |
import Peer from 'peerjs'; | |
const usePeer = ({ id, host, port, path, onOpen, onConnection, onDisconnection, onClose, onError, onMessage }) => { | |
const [peer, setPeer] = useState(); | |
const [peerId, setPeerId] = useState(); | |
const [connection, setConnection] = useState(); | |
const [message, setMessage] = useState(); | |
const onPeerOpen = useCallback((current) => { | |
setPeer(current); | |
setPeerId(current.id); | |
onOpen && onOpen(current); | |
}, [onOpen]); | |
const onPeerDisconnected = useCallback(() => { | |
onDisconnection && onDisconnection() | |
}, [onDisconnection]); | |
const onPeerClose = useCallback(() => { | |
onClose && onClose() | |
}, [onClose]); | |
const onPeerError = useCallback((error) => { | |
onError && onError(error) | |
}, [onError]); | |
const onPeerConnected = useCallback((newConnection) => { | |
if (connection) { | |
newConnection.close(); | |
return; | |
} | |
setConnection(newConnection); | |
}, [connection]); | |
const onData = useCallback((data) => { | |
onMessage && onMessage(data); | |
setMessage(data); | |
}, [onMessage]); | |
const onConnectionOpen = useCallback(() => { | |
if (connection) { | |
onConnection && onConnection(); | |
connection.on('data', onData); | |
connection.on('close', onPeerClose); | |
} | |
}, [connection, onConnection, onPeerClose, onData]); | |
useEffect(() => { | |
const current = peer || new Peer({ host, port, path }); | |
current.on('open', () => onPeerOpen(current)); | |
current.on('error', onPeerError); | |
current.on('close', onPeerClose); | |
current.on('disconnected', onPeerDisconnected); | |
current.on('connection', onPeerConnected); | |
}, [host, port, path, peer, onPeerOpen, onPeerClose, onPeerError, onPeerConnected, onPeerDisconnected]) | |
useEffect(() => { | |
if (connection) { | |
connection.on('open', onConnectionOpen); | |
} | |
}, [connection, onConnectionOpen]) | |
const connect = (targetId) => { | |
if (!targetId || targetId === peerId) { | |
return; | |
} | |
const current = peer.connect(targetId); | |
setConnection(current); | |
} | |
const send = (message) => { | |
if (connection) { | |
connection.send(message); | |
} | |
}; | |
return { | |
id: peerId, | |
connected: !!connection, | |
close: () => { | |
peer && peer.destroy(); | |
setConnection(null); | |
}, | |
join: connect, | |
send, | |
message | |
} | |
}; | |
export default usePeer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment