Skip to content

Commit

Permalink
Fix: clients appearing multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
Core447 committed Jan 1, 2025
1 parent a792451 commit de92512
Showing 1 changed file with 36 additions and 7 deletions.
43 changes: 36 additions & 7 deletions src/app/com/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import { DataConnection, Peer } from "peerjs";
import { use, useCallback, useEffect, useMemo, useState } from "react";
import { adjectives, animals, colors, uniqueNamesGenerator } from "unique-names-generator";

interface Data {
name: string
}

export default function Page() {
const [connectedCons, setConnectedCons] = useState<DataConnection[]>([]);
const [connectingTo, setConnectingTo] = useState<string | null>(null);
const [once, setOnce] = useState(false);

const peerName = useMemo(() => {
// Just for easier testing - discovery either via fastapi backend or next.js server
Expand All @@ -21,6 +23,19 @@ export default function Page() {
});
}, []);

const addConnection = useCallback((conn: DataConnection) => {
setConnectedCons(prev => {
const exists = prev.some(c => c.peer === conn.peer); // we cant use connectedCons for checking, but have to use prev as we call addConnection multiple times before the next re-render when the connectedCons updates
if (exists) return prev;
return [...prev, conn];
});
}, []);

useEffect(() => {
const usedIds = connectedCons.map((c) => c.peer);
console.log("used ids", usedIds);

}, [connectedCons]);

const peer = useMemo(() => {
const peer = new Peer(peerName);
Expand All @@ -43,35 +58,41 @@ export default function Page() {
conn.on("open", () => {
conn.send("hello");
console.log(`connected to ${otherPeerName}`);
setConnectedCons((prev) => [...prev, conn]);
// setConnectedCons((prev) => [...prev, conn]);
addConnection(conn);
});
})
}
loadConnections();

return peer;
}, [peerName]);
}, [peerName, addConnection]);



useEffect(() => {
peer.on("connection", (conn) => {
setConnectedCons((prev) => [...prev, conn]);
// setConnectedCons((prev) => [...prev, conn]);
conn.on("open", () => {
addConnection(conn);
// console.log("connection open");
})
conn.on("data", (data) => {
console.log("received data", data);
});
});
}, [peer]);
}, [peer, addConnection]);


function sendToAll2() {
console.log(`sending to all ${connectedCons.length} connections`);
connectedCons.forEach((conn) => {
if (conn.open) {
conn.send("sendToAll");
// conn.send("sendToAll");
const data: Data = {
name: "cool name"
}
conn.send(data);
} else {
console.warn("Connection is not open:", conn);
}
Expand All @@ -82,6 +103,14 @@ export default function Page() {
<div>
<p>Peer id: {peer.id}</p>
<button onClick={sendToAll2}>Send To All</button>
<h1>connections:</h1>
{connectedCons.map((conn, index) => {
return (
<div key={index}>
<p>{conn.peer}</p>
</div>
);
})}
</div>
);
}

0 comments on commit de92512

Please sign in to comment.