1
Fork 0
mirror of https://github.com/Steffo99/todocolors.git synced 2024-11-22 16:24:19 +00:00

Create initial board viewer page

This commit is contained in:
Steffo 2023-07-30 02:21:29 +02:00
parent c832166e2a
commit 1536b495c7
Signed by: steffo
GPG key ID: 2A24051445686895
3 changed files with 61 additions and 0 deletions

View file

@ -0,0 +1,15 @@
'use client';
import {default as React} from "react";
import {useBoard} from "@/app/board/[board]/useBoard"
export default function Page({params: {board}}: {params: {board: string}}) {
const wsUrl = React.useMemo(() => `ws://127.0.0.1:8080/board/${board}/ws`, [board])
useBoard(wsUrl);
return (
<p>
TODO
</p>
)
}

View file

@ -0,0 +1,16 @@
'use client';
import {default as React} from "react";
import {useWs} from "@/app/board/[board]/useWs"
export function useBoard(url: string) {
const socket = useWs(url, {
onopen: React.useCallback(() => {
console.debug("[useBoard] Connected to the server!");
}, []),
onmessage: React.useCallback((event: MessageEvent) => {
const data = JSON.parse(event.data);
console.debug("[useBoard] Received ServerOperation: ", data);
}, [])
});
}

View file

@ -0,0 +1,30 @@
'use client';
import {default as React} from "react";
export interface UseWsHandlers {
onclose?: (event: CloseEvent) => void,
onerror?: (event: Event) => void,
onmessage?: (event: MessageEvent) => void,
onopen?: (event: Event) => void,
}
export function useWs(url: string, {onclose, onerror, onmessage, onopen}: UseWsHandlers) {
const [websocket, setWebsocket] = React.useState<WebSocket | null>(null)
React.useEffect(() => {
const sock = new WebSocket(url);
sock.onclose = onclose ?? null;
sock.onerror = onerror ?? null;
sock.onmessage = onmessage ?? null;
sock.onopen = onopen ?? null;
setWebsocket(sock);
return () => {
sock.close();
setWebsocket(null);
}
}, [url, onclose, onerror, onmessage, onopen])
return websocket
}