fix: Bug where socket gets two event listeners

This commit is contained in:
Joel Therrien 2024-12-26 15:15:03 -08:00
parent 1c81740baa
commit db5da6801b

View file

@ -1,5 +1,5 @@
import * as React from "react";
import {useState} from "react";
import {useRef, useState} from "react";
import {createRoot} from "react-dom/client";
import {AISelection} from "./UI";
import {ClientToServerMessage, WSAPI, PartyInfo, ServerToClientMessage} from "./ws_api";
@ -25,6 +25,8 @@ export function Menu(): React.JSX.Element {
const [aiRandomness, setAIRandomness] = useState<number>(6);
const [proportionDictionary, setProportionDictionary] = useState<number>(7);
const gameAPI = useRef<WSAPI>(null);
const [game, setGame] = useState<React.JSX.Element>(null);
const validSettings = roomName.length > 0 && !roomName.includes("/") && playerName.length > 0 && !playerName.includes("?") && !playerName.includes("&");
@ -89,6 +91,7 @@ export function Menu(): React.JSX.Element {
socket.close();
setSocket(null);
setPartyInfo(null);
gameAPI.current = null;
}}>Disconnect
</button>
<button onClick={() => {
@ -122,14 +125,17 @@ export function Menu(): React.JSX.Element {
<button
disabled={!validSettings}
onClick={() => {
let socket = new WebSocket(`/room/${roomName}?player_name=${playerName}`)
let socket = new WebSocket(`ws://localhost:8000/room/${roomName}?player_name=${playerName}`);
socket.addEventListener("message", (event) => {
const input: ServerToClientMessage = JSON.parse(event.data);
if (input.type == "RoomChange") {
setPartyInfo(input.info);
} else if (input.type == "GameEvent" && game == null) {
// start game
setGame(<Game api={new WSAPI(socket)} settings={{
if(gameAPI.current == null) {
gameAPI.current = new WSAPI(socket);
}
setGame(<Game api={gameAPI.current} settings={{
playerName: playerName,
trayLength: 7,
}} end_game_fn={function (): void {
@ -137,15 +143,17 @@ export function Menu(): React.JSX.Element {
setSocket(null);
setPartyInfo(null);
setGame(null);
gameAPI.current = null;
}}/>);
}
console.log("Message from server ", event.data);
//console.log("Message from server ", event.data);
});
socket.addEventListener("close", (event) => {
console.log({event});
setSocket(null);
setPartyInfo(null);
setGame(null);
gameAPI.current = null;
if (event.reason != null && event.reason.length > 0) {
alert(`Disconnected with reason "${event.reason} & code ${event.code}"`);
}