Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

M3 check roomlist before enter #100

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/components/views/Gameroom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ const Gameroom = () => {

useEffect(() => {
const isChrome = (window as any).chrome;
console.error("ISCHROME",isChrome);
// console.error("ISCHROME",isChrome);
if (!isChrome) {
alert("Please use Chrome browser to play the game.");
navigate("/lobby");
Expand Down
140 changes: 88 additions & 52 deletions src/components/views/Lobby.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useRef, useEffect, useState } from "react";
import { api, handleError } from "helpers/api";
import { Button } from "components/ui/Button";
import { useNavigate } from "react-router-dom";
import { useLocation, useNavigate } from "react-router-dom";
import BaseContainer from "components/ui/BaseContainer";
import PropTypes from "prop-types";
import { User, Room } from "types";
Expand Down Expand Up @@ -137,6 +137,8 @@ const Lobby = () => {
const [roomName, setRoomName] = useState("");
const [numRounds, setNumRounds] = useState(2);
const [roomTheme, setRoomTheme] = useState("");
// const needReloadRooms = useRef(false);
// const RELOAD_TIME = 3000;

const logout = async () => {
const id = sessionStorage.getItem("id");
Expand All @@ -152,66 +154,91 @@ const Lobby = () => {
navigate("/login");
};
async function fetchData() {
try {
// 获取所有房间信息
const roomsResponse = await api.get("/games/lobby");
console.log("Rooms data:", roomsResponse.data);

// 使用 Promise.all 来并发获取每个房间的用户详细信息
const roomsWithPlayerDetails = await Promise.all(roomsResponse.data.map(async (room) => {
// 对每个房间的用户 ID 列表并发请求用户信息
const playerDetails = await Promise.all(room.roomPlayersList.map(async (userId) => {
const userResponse = await api.get(`/users/${userId}`);

return userResponse.data; // 返回用户的详细信息
}));

return {
...room,
roomPlayersList: playerDetails // 替换房间中的用户 ID 列表为用户详细信息
};
}));
// try {
// 获取所有房间信息
const roomsResponse = await api.get("/games/lobby");
console.log("Rooms data:", roomsResponse.data);

// 使用 Promise.all 来并发获取每个房间的用户详细信息
const roomsWithPlayerDetails = await Promise.all(roomsResponse.data.map(async (room) => {
// 对每个房间的用户 ID 列表并发请求用户信息
const playerDetails = await Promise.all(room.roomPlayersList.map(async (userId) => {
const userResponse = await api.get(`/users/${userId}`);

// 更新房间状态,包含了用户的详细信息
setRooms(roomsWithPlayerDetails);
return userResponse.data; // 返回用户的详细信息
}));

// needReloadRooms.current = false;

console.log("request to:", roomsResponse.request.responseURL);
console.log("status code:", roomsResponse.status);
console.log("status text:", roomsResponse.statusText);
console.log("requested data:", roomsResponse.data);
// setTimeout(() => {
// needReloadRooms.current = true;
// }, RELOAD_TIME);

// See here to get more data.
console.log(roomsResponse);
return {
...room,
roomPlayersList: playerDetails // 替换房间中的用户 ID 列表为用户详细信息
};
}));

// Get user ID from sessionStorage
const userId = sessionStorage.getItem("id");
if (userId) {
// Get current user's information
const userResponse = await api.get(`/users/${userId}`);
setUser(userResponse.data); // Set user data from API
console.log("User data:", userResponse.data);
} else {
console.log("No user ID found in sessionStorage.");
}
} catch (error) {
console.error(
`Something went wrong while fetching the users: \n${handleError(
error
)}`
);
console.error("Details:", error);
alert(
"Something went wrong while fetching the users! See the console for details."
);
// 更新房间状态,包含了用户的详细信息
setRooms(roomsWithPlayerDetails);

console.log("request to:", roomsResponse.request.responseURL);
console.log("status code:", roomsResponse.status);
console.log("status text:", roomsResponse.statusText);
console.log("requested data:", roomsResponse.data);

// See here to get more data.
console.log(roomsResponse);

// Get user ID from sessionStorage
const userId = sessionStorage.getItem("id");
if (userId) {
// Get current user's information
const userResponse = await api.get(`/users/${userId}`);
setUser(userResponse.data); // Set user data from API
console.log("User data:", userResponse.data);
} else {
console.log("No user ID found in sessionStorage.");
}
// } catch (error) {
// console.error(
// `Something went wrong while fetching the users: \n${handleError(
// error
// )}`
// );
// console.error("Details:", error);
// alert(
// "Something went wrong while fetching the users! See the console for details."
// );
// }
}

useEffect(() => {
fetchData().catch(error => {
console.error("Unhandled error in fetchData:", error);
navigate("/login");
});
}, []);

// when user get navigated back to this page, fetch data again
const location = useLocation();
// console.warn("Location:", location);
useEffect(() => {
// wait for 1 second before fetching data
const timeoutId = setTimeout(() => {
console.log("========fetchData========");
fetchData().catch(error => {
console.error("Unhandled error in fetchData:", error);
navigate("/login");
});
}, 500);

return () => {
clearTimeout(timeoutId);
}
}, [location]);

const doEdit = async () => {
try {
const requestBody = JSON.stringify({ username: username, avatar: avatar });
Expand Down Expand Up @@ -348,15 +375,24 @@ const Lobby = () => {
username: newUsername // 更新 avatar 属性
}));
};
const userinfo = () => {
return;
};


const renderRoomLists = () => {
return rooms.map((Room) => (
<div className="room-container" key={Room.roomId} onClick={(e) => {
<div className="room-container" key={Room.roomId} onClick={async (e) => {
e.preventDefault();

/// when user click the room, fetch the data again
/// and check if the room is still in the list
await fetchData();
// check if roomId is still in the list
const room = rooms.find(r => r.roomId === Room.roomId);
if (!room) {
alert("The room's info is outdated, please try again!");

return;
}

const currentId = sessionStorage.getItem("id");
const isPlayerInRoom = Room.roomPlayersList.join().includes(currentId);
enterRoom(Room.roomId, currentId)
Expand Down