import { useEffect, useState, useCallback } from 'react' import { useParams } from 'react-router-dom' import dayjs from 'dayjs' import utc from 'dayjs/plugin/utc' dayjs.extend(utc) import PM from './PM' import MessageInput from './MessageInput' import UserInfo from './UserInfo' import { getChat, pm } from '../api' import { useVisitor } from './VisitorContext' import { Helmet } from 'react-helmet-async' /** * * @typedef {object} ChatProps * @property {EventSource} connection */ /** * Chat component * @param {ChatProps} props */ export default function Chat(props) { const [visitor] = useVisitor() const [messages, setMessages] = useState([]) const params = useParams() let loadChat = useCallback((uname) => { const { hash } = visitor if (hash && uname) { getChat(uname) .then(response => { setMessages(response.data) }).catch(console.log) } }, [visitor]) let onMessage = useCallback((json) => { const msg = JSON.parse(json.data) if (msg.user.uname === params.user) { setMessages((oldChat) => { return [msg, ...oldChat] }) } }, [params.user]) let onSend = async ({ body }) => { let result = false let res = await pm(params.user, body).catch(console.error) result = res.status == 200 return result } useEffect(() => { if (props.connection.addEventListener) { props.connection.addEventListener('msg', onMessage) } loadChat(params.user) console.log(props.connection) return () => { if (props.connection.removeEventListener) { props.connection.removeEventListener('msg', onMessage) } } }, [props.connection, onMessage, loadChat, params.user]) const uname = params.user return (
No chat selected