From 7c9809d661fb4738117ee9df24618afeccf84058 Mon Sep 17 00:00:00 2001 From: yixuan-zhou-uzh Date: Tue, 7 May 2024 22:44:07 +0200 Subject: [PATCH] [feat] join to a room fuction extracted and throttling added fix #136 --- src/components/views/Lobby.tsx | 42 ++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/src/components/views/Lobby.tsx b/src/components/views/Lobby.tsx index ba7d259..60b08b1 100644 --- a/src/components/views/Lobby.tsx +++ b/src/components/views/Lobby.tsx @@ -3,6 +3,7 @@ import { showToast } from "helpers/toastService"; import { v4 as uuidv4 } from "uuid"; import { api, handleError } from "helpers/api"; import { Button } from "components/ui/Button"; +import { throttle } from "lodash"; import { useLocation, useNavigate } from "react-router-dom"; import BaseContainer from "components/ui/BaseContainer"; import PropTypes from "prop-types"; @@ -18,6 +19,7 @@ import { over } from "stompjs"; import { Timestamped, RoomInfo, RoomPlayer, PlayerAndRoomID } from "stomp_types"; const DEFAULT_MAX_PLAYERS = 5; const DEFAULT_MIN_PLAYERS = 2; +const RESPONSE_TIME = 1000; type PlayerProps = { user: User; @@ -489,29 +491,29 @@ const Lobby = () => { } } + const throttledClickHandler = throttle((Room, navigate, showToast) => { + try { + if (Room.roomPlayersList.length === Room.roomMaxNum) { + showToast("Room is Full, please enter another room!", "error"); + } else if (Room.status === "In Game") { + showToast("Game is already started, please enter another room!", "error"); + } else { + navigate(`/rooms/${Room.roomId}/${Room.roomName}`); + } + } catch (error) { + console.error(`Something went wrong during the enterRoom: \n${error}`); + showToast(`Something went wrong during the enterRoom: \n${error}`, "error"); + } + }, RESPONSE_TIME); + + const handleRoomClick = useCallback((Room) => (e) => { + e.preventDefault(); + throttledClickHandler(Room, navigate, showToast); + }, [navigate, showToast]); const renderRoomLists = () => { return rooms.map((Room) => ( -
{ - e.preventDefault(); - // const currentId = sessionStorage.getItem("id"); - // console.error("RoomMaxPlayers:", Room.roomMaxNum); - // console.error("RoomPlayersList.length:", Room.roomPlayersList.length); - try { - if (Room.roomPlayersList.length === Room.roomMaxNum) - showToast("Room is Full, please enter another room!", "error"); - else if (Room.status === "In Game") - showToast("Game is already started, please enter another room!", "error"); - else - navigate(`/rooms/${Room.roomId}/${Room.roomName}`); - } - catch (error) { - console.error(`Something went wrong during the enterRoom: \n${error}`); - // alert(`Something went wrong during the enterRoom: \n${error}`); - showToast(`Something went wrong during the enterRoom: \n${error}`, "error"); - }; - - }}> +
{Room.roomPlayersList?.map((user, index) => (