import React, { Component } from 'react'; import { w3cwebsocket as W3CWebSocket } from "websocket"; import {Button, TextField, Link, Grid, Typography, Container, Card, CardHeader, Paper, Avatar} from "@mui/material"; import { withStyles } from "@mui/material"; export default class Chat extends Component { constructor(props) { super(props); } state = { messages: [], value:'', orderId: 2, }; client = new W3CWebSocket('ws://' + window.location.host + '/ws/chat/' + this.props.data.orderId + '/'); componentDidMount() { this.client.onopen = () => { console.log('WebSocket Client Connected') console.log(this.props.data) } this.client.onmessage = (message) => { const dataFromServer = JSON.parse(message.data); console.log('Got reply!', dataFromServer.type); if (dataFromServer){ this.setState((state) => ({ messages: [...state.messages, { msg: dataFromServer.message, userNick: dataFromServer.user_nick, }], }) ) } } } onButtonClicked = (e) => { this.client.send(JSON.stringify({ type: "message", message: this.state.value, nick: this.props.data.urNick, })); this.state.value = '' e.preventDefault(); } render() { return ( {this.state.messages.map(message => <> {/* {message.userNick == this.props.data.urNick ? align='right' : align='left'} */} } title={message.userNick} subheader={message.msg} /> )}
{ this.setState({ value: e.target.value }); this.value = this.state.value; }} />
) } }