From fccc23c05712b0b54e77daefd4b74855e52f08b6 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 8 Apr 2019 15:42:24 +0300 Subject: App, Chat, Thread using hooks --- vnext/src/components/Chat.js | 98 +++++++++++++++++++++----------------------- 1 file changed, 46 insertions(+), 52 deletions(-) (limited to 'vnext/src/components/Chat.js') diff --git a/vnext/src/components/Chat.js b/vnext/src/components/Chat.js index 57415d29..e2b8d2f1 100644 --- a/vnext/src/components/Chat.js +++ b/vnext/src/components/Chat.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useEffect, useState } from 'react'; import ReactRouterPropTypes from 'react-router-prop-types'; import { UserType } from './Types'; import moment from 'moment'; @@ -11,74 +11,68 @@ import { getChat, pm } from '../api'; import './Chat.css'; -export default class Chat extends React.Component { - constructor(props) { - super(props); - - this.state = { - chats: [] +export default function Chat(props) { + const [chats, setChats] = useState([]); + useEffect(() => { + console.log(props.connection); + if (props.connection) { + props.connection.addEventListener('msg', onMessage); + } + loadChat(props.match.params.user); + return () => { + if (props.connection) { + props.connection.removeEventListener('msg', onMessage); + } }; - } - componentDidMount() { - this.loadChat(this.props.match.params.user); - } + }, [props.connection]); - loadChat = (uname) => { - const { hash } = this.props.visitor; - this.setState({ - chats: [] - }); + let loadChat = (uname) => { + const { hash } = props.visitor; + setChats([]); if (hash && uname) { getChat(uname) .then(response => { - this.setState({ - chats: response.data - }); + setChats(response.data); }); } } - onMessage = (msg) => { - if (msg.user.uname === this.props.match.params.user) { - this.setState({ - chats: [msg, ...this.state.chats] - }); + let onMessage = (json) => { + const msg = JSON.parse(json.data); + if (msg.user.uname === props.match.params.user) { + setChats([msg, ...chats]); } } - onSend = (template) => { + let onSend = (template) => { pm(template.to.uname, template.body) .then(res => { - this.loadChat(this.props.match.params.user); + loadChat(props.match.params.user); }).catch(console.log); } - - render() { - const { chats } = this.state; - const uname = this.props.match.params.user; - return ( -
- - {uname ? ( -
-
    - { - chats.map((chat) => - - ) - } -
- - Reply... + const uname = props.match.params.user; + return ( +
+ + {uname ? ( +
+
    + { + chats.map((chat) => + + ) + } +
+ + Reply... -
- ) : ( -

No chat selected

- ) - } -
- ); - } +
+ ) : ( +

No chat selected

+ ) + } +
+ ); } Chat.propTypes = { -- cgit v1.2.3