hermes-web/app/socket/page.tsx

58 lines
1.5 KiB
TypeScript

"use client"
import { Button } from '@/components/ui/button';
import { v4 } from "uuid"
import { useEffect, useState } from 'react';
import useWebSocket from 'react-use-websocket';
const socketUrl = 'wss://echo.websocket.org';
const SocketPage = () => {
const [mounted, setMounted] = useState(false)
const {
sendMessage,
sendJsonMessage,
lastMessage,
lastJsonMessage,
readyState,
getWebSocket,
} = useWebSocket(socketUrl, {
onOpen: () => console.log('opened'),
onMessage: (e) => console.log("MESSAGE", e),
onError: (e) => console.error(e),
shouldReconnect: (closeEvent) => { console.log("Reconnect"); return true; },
});
const [messageHistory, setMessageHistory] = useState<MessageEvent[]>([]);
useEffect(() => {
if (lastMessage !== null) {
console.log("LAST", lastMessage)
setMessageHistory((prev) => prev.concat(lastMessage));
}
}, [lastMessage, setMessageHistory]);
useEffect(() => {
if (!mounted) {
setMounted(true)
}
}, [])
return (<div className="w-full bg-blue-300">
<p>Hello</p>
<p>{readyState}</p>
<Button onClick={() => sendMessage("uisdhnishdadasdfsd " + v4())}>
Click on me
</Button>
<div>
{lastMessage ? <span>Last message: {lastMessage.data}</span> : null}
<ul>
{messageHistory.map((message, idx) => (
<p className='block' key={idx}>{message ? message.data : null}</p>
))}
</ul>
</div>
</div>)
}
export default SocketPage