import React, { useEffect, useState, useCallback } from 'react'; import moment from 'moment'; import PM from './PM'; import MessageInput from './MessageInput'; import UserInfo from './UserInfo'; import { getChat, pm } from '../api'; import './Chat.css'; /** * @typedef {Object} ChatProps * @property {import('../api').SecureUser} visitor * @property {EventSource} connection * @property {import('react-router').match} match */ /** * Chat component * @param {ChatProps} props */ export default function Chat(props) { const [chats, setChats] = useState([]); let loadChat = useCallback((uname) => { const { hash } = props.visitor; setChats([]); if (hash && uname) { getChat(uname) .then(response => { setChats(response.data); }); } }, [props.visitor]); let onMessage = useCallback((json) => { const msg = JSON.parse(json.data); if (msg.user.uname === props.match.params.user) { setChats((oldChat) => { return [msg, ...oldChat]; }); } }, [props.match.params.user]); let onSend = (template) => { pm(template.to.uname, template.body) .then(res => { loadChat(props.match.params.user); }).catch(console.log); }; useEffect(() => { if (props.connection.addEventListener) { props.connection.addEventListener('msg', onMessage); } loadChat(props.match.params.user); console.log(props.connection); return () => { if (props.connection.removeEventListener) { props.connection.removeEventListener('msg', onMessage); } }; }, [props.connection, onMessage, loadChat, props.match.params.user]); const uname = props.match.params.user; return (
No chat selected