Created
April 22, 2024 18:23
-
-
Save rayanfer32/5127b24c3237c6a5dc72d7680d24c572 to your computer and use it in GitHub Desktop.
A useful hook to keep state synced across all the connected peers
This file contains 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 { useCallback, useEffect, useRef, useState } from "react"; | |
export default function usePeerStateSync( | |
initialState, | |
peer, | |
onConnection, | |
isHost | |
) { | |
const [state, setState] = useState(initialState); | |
// ! Ref hack to use latest value of isHost | |
const isHostRef = useRef(isHost); | |
isHostRef.current = isHost; | |
function handleSync(data) { | |
console.log("isHost: ", isHostRef.current); | |
if (isHostRef.current) { | |
sync(data); | |
} | |
} | |
const registerConnection = useCallback( | |
function (connection) { | |
connection.on("data", (data) => { | |
if (data.type == "state") { | |
console.log("recieved update"); | |
setState(data.data); | |
// * send the state updates to all the nodes | |
handleSync(data.data); | |
} | |
}); | |
}, | |
[peer] | |
); | |
useEffect(() => { | |
peer.on("connection", (conn) => { | |
conn.on("error", console.log); | |
conn.on("open", () => { | |
console.log("Connection Established"); | |
onConnection(peer.connections); | |
registerConnection(conn); | |
}); | |
}); | |
return () => { | |
peer.removeAllListeners(); | |
}; | |
}, [peer]); | |
function sync(data) { | |
console.log(peer.connections); | |
Object.values(peer.connections).forEach((connArr) => { | |
connArr[0].send({ type: "state", data: data }); | |
}); | |
} | |
function _setState(data) { | |
setState(data); | |
sync(data); | |
} | |
return [state, _setState, registerConnection]; | |
} | |
// Usage: | |
const [sharedState, setSharedState, registerConnection] = usePeerStateSync( | |
"Change me!", | |
peer, | |
onConnection, | |
isHost | |
); | |
useEffect(() => { | |
peer.on("error", alert); | |
peer.on("open", function (id) { | |
console.log("My peer ID is: " + id); | |
setPeerId(id); | |
}); | |
return () => { | |
// peer.removeAllListeners(); | |
}; | |
}, []); | |
function handleConnect() { | |
let connection = peer.connect(BASE_IDENTIFIER + connectToId); | |
connection.on("open", () => { | |
connection.on("error", console.log); | |
console.log("Connection established"); | |
setConnections(peer.connections); | |
registerConnection(connection); | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment