more logging stuff
This commit is contained in:
46
frontend/src/hooks/socket.io.hook.ts
Normal file
46
frontend/src/hooks/socket.io.hook.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import socket from "@/lib/socket.io";
|
||||
|
||||
export function useSocketRoom<T>(roomId: string) {
|
||||
const [data, setData] = useState<T[]>([]);
|
||||
const [info, setInfo] = useState(
|
||||
"No data yet — join the room to start receiving",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
function handleConnect() {
|
||||
socket.emit("join-room", roomId);
|
||||
}
|
||||
|
||||
function handleUpdate(payload: any) {
|
||||
setData((prev) => [...payload.payloads, ...prev]);
|
||||
}
|
||||
|
||||
function handleError(err: any) {
|
||||
setInfo(err.message ?? "Room error");
|
||||
}
|
||||
|
||||
if (!socket.connected) {
|
||||
socket.connect();
|
||||
}
|
||||
|
||||
socket.on("connect", handleConnect);
|
||||
socket.on("room-update", handleUpdate);
|
||||
socket.on("room-error", handleError);
|
||||
|
||||
// If already connected, join immediately
|
||||
if (socket.connected) {
|
||||
socket.emit("join-room", roomId);
|
||||
}
|
||||
|
||||
return () => {
|
||||
socket.emit("leave-room", roomId);
|
||||
|
||||
socket.off("connect", handleConnect);
|
||||
socket.off("room-update", handleUpdate);
|
||||
socket.off("room-error", handleError);
|
||||
};
|
||||
}, [roomId]);
|
||||
|
||||
return { data, info };
|
||||
}
|
||||
Reference in New Issue
Block a user