'use client' /* eslint-disable @typescript-eslint/no-explicit-any */ import React, { useEffect, useRef, useState } from 'react' import { Socket } from 'socket.io'; import { io } from 'socket.io-client'; import { socket } from './socket'; import Link from 'next/link'; // https://www.baeldung.com/webrtc export default function ChatWS() { const [session, setSession] = useState<{ who: string, room?: string }>() const [messages, setMessages] = useState<{ who: string, msg: string }[]>([]) const nameRef = useRef(null) useEffect(() => { socket.onAny((ev, data) => { console.log(`ANY`, ev, data) // setMessages(prevMessages => [...prevMessages, data]); }); socket.on('chat message', (data) => { // console.log(`chat message`,data) setMessages(prevMessages => [...prevMessages, data]); }); // Clean up the listener when the component unmounts return () => { socket.off('chat message'); }; }, []) if (!session?.who) return
{ // ev.preventDefault() // const form = new FormData(ev.target) // alert(form.get(`name`)) // setSession((s: any) => { // return { // ...s, // who: form.get(`name`) // } // }) // }} className='bg-white/10 backdrop-blur-lg w-96 h-64 flex flex-col border border-white/20 shadow-lg p-2'>
Enter a name to use in this chat
return (
{messages.map((msg, i) =>
{msg.who} {msg.msg}
)}
{/* {JSON.stringify(messages)} */}
All message are removed once you leave this chat
{ ev.preventDefault() const form = new FormData(ev.target) if (!form.get('msg')) return socket.emit('chat message', { who: session!.who ?? 'Annonymous', msg: form.get('msg') as string }) ev.currentTarget.reset() }} className='flex p-2 bg-gray-100 shadow-2xl opacity-90' >
) }