64 lines
1.7 KiB
TypeScript
64 lines
1.7 KiB
TypeScript
import useWebSocket from "react-use-websocket";
|
|
import React from "react";
|
|
import {useParams} from "react-router";
|
|
import {GHButton} from "../components/Button";
|
|
import useTitle from "../../utils/TitleHook";
|
|
|
|
const Room = () => {
|
|
|
|
useTitle('Mau!');
|
|
|
|
const {roomId} = useParams();
|
|
|
|
const WS_URL = `ws://${process.env.REACT_APP_API_URL}/room/${roomId}`;
|
|
|
|
const [message, setMessage] = React.useState<string>('');
|
|
const [messages, setMessages] = React.useState<string[]>([]);
|
|
|
|
const websocket = useWebSocket(WS_URL, {
|
|
onOpen: () => {
|
|
console.log('WebSocket connection established.');
|
|
},
|
|
onMessage: (event) => {
|
|
setMessages([...messages, event.data]);
|
|
}
|
|
});
|
|
|
|
const handleSend = () => {
|
|
websocket.sendMessage(message);
|
|
setMessage('');
|
|
}
|
|
|
|
const handleMessageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
|
setMessage(event.target.value);
|
|
}
|
|
|
|
const handleLeaveRoom = () => {
|
|
window.location.href = '/';
|
|
}
|
|
|
|
return (
|
|
<div>
|
|
<h1>Room {roomId}</h1>
|
|
<GHButton onClick={handleLeaveRoom}>Leave Room</GHButton>
|
|
<form onSubmit={(event) => {
|
|
event.preventDefault();
|
|
handleSend();
|
|
}}>
|
|
<input type="text" name="message" placeholder="Send a message" value={message}
|
|
onChange={handleMessageChange}/>
|
|
<span onClick={handleSend}>Send</span>
|
|
</form>
|
|
<ul>
|
|
{
|
|
messages.map((message, index) => {
|
|
return <li key={index}>{message}</li>
|
|
})
|
|
}
|
|
</ul>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
export default Room;
|