Generateurv2/frontend/components/room/WaitingRoom.jsx

76 lines
1.8 KiB
React
Raw Normal View History

2022-05-18 10:15:54 +02:00
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { useWebsocketContext } from "../../context/websocket.context.js";
import { checkRoom } from "../../requests/requests.room.js";
import { isBrowser } from "../../utils/utils.js";
import Layout from "../Layout.js";
export default function WaitingRoom() {
const router = useRouter();
2022-06-24 13:42:16 +02:00
const {
isConnected,
send,
connect,
addMessageHandler,
removeMessageHandler,
disconnect,
} = useWebsocketContext();
2022-05-18 10:15:54 +02:00
useEffect(() => {
2022-06-24 13:42:16 +02:00
if (isBrowser && (sessionStorage.getItem('waiter') == null || sessionStorage.getItem('waiter_nick') == null)) {
router.push({ pathname: `/room/join${router.query.mode[1]}` });
}
2022-05-18 10:15:54 +02:00
if (isConnected == false && isBrowser) {
2022-06-24 13:42:16 +02:00
checkRoom(router.query.mode[1])
.then(() => {
console.log('CONNECT HERE TO')
connect(`ws://192.168.1.18:8000/ws/room/${router.query.mode[1]}`);
send({
data: {
type: "login",
nick: sessionStorage.getItem("waiter_nick"),
},
});
})
.catch(() => {
router.push({ pathname: "/room/join" });
});
2022-05-18 10:15:54 +02:00
}
}, [isConnected]);
useEffect(() => {
let handler = (e) => {
let data = JSON.parse(e.data);
let type = data.type;
2022-06-24 13:42:16 +02:00
switch (type) {
case "refused":
sessionStorage.clear();
2022-05-18 10:15:54 +02:00
{
2022-06-24 13:42:16 +02:00
router.push({ pathname: "/room/join" });
2022-05-18 10:15:54 +02:00
}
default:
2022-06-24 13:42:16 +02:00
return;
2022-05-18 10:15:54 +02:00
}
2022-06-24 13:42:16 +02:00
};
addMessageHandler(handler);
2022-05-18 10:15:54 +02:00
return () => {
2022-06-24 13:42:16 +02:00
removeMessageHandler(handler);
};
}, []);
useEffect(() => {
return () => {
disconnect();
};
}, []);
return (
<Layout page="En attente...">
<p>Waiting Room</p>
</Layout>
);
2022-05-18 10:15:54 +02:00
}