Chat.js 4.19 KB
Newer Older
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
1
import axios from 'axios';
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
2
import React, { useState, useEffect } from 'react';
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
3
4
5
import { Form, Button, Row, Image, Col, Container } from 'react-bootstrap';
import { isAuthenticated } from '../utils/auth';
import catchErrors from '../utils/catchErrors';
우지원's avatar
ul    
우지원 committed
6
7
8


function Chat(props) {
Choi Ga Young's avatar
Choi Ga Young committed
9
  // let defaultname = sessionStorage.getItem('name');
JeongYeonwoo's avatar
JeongYeonwoo committed
10

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
11
  const [inner, setInner] = useState([''])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
12
  const [chat, setChat] = useState([])   //object로 key는 보낸사람 value는 메세지
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
13
  const [disabled, setDisabled] = useState(true)
Choi Ga Young's avatar
Choi Ga Young committed
14
15
  const [user, setUser] = useState('')
  const [error, setError] = useState('');
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
16
17
18
19
20
21
22
23
24
25
26

  const userId = isAuthenticated()
  async function getProfile(userId) {
    try {
      const response = await axios.get(`/users/${userId}`)
      setUser(response.data)
    } catch (error) {
      catchErrors(error, setError)
    }
  }

27
28
  function handleChange(e) {
    e.preventDefault()
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
29
    setInner(e.target.value)
30
    console.log(e.target.value)
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
31
    setDisabled(false)
32
33
34
  }

  function sendMsgCH(e) {
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
35
36
    e.preventDefault()
    props.setSingleChat(inner)
37
    props.sendMsg(e)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
38
    setInner('')
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
39
40
    setDisabled(true)
    console.log(chat)
41
  }
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
42
43
44
  useEffect(() => {
    getProfile(userId)
  }, [userId])
45

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
46
47
  useEffect(() => {
    setChat([...chat, props.singleChat])
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
48
49
    console.log('UseEffect singlechat', chat)
    // check()
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
50
  }, [props.singleChat])
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
51

JeongYeonwoo's avatar
JeongYeonwoo committed
52
53
  useEffect(() => {
    setChat([...chat, props.recievedMsg])
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
54
    console.log('UseEffect recievechat', chat)
JeongYeonwoo's avatar
JeongYeonwoo committed
55
  }, [props.recievedMsg])
Choi Ga Young's avatar
aa    
Choi Ga Young committed
56

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
57
  const time = new Date().toLocaleTimeString()
우지원's avatar
ul    
우지원 committed
58
  return (
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
59
    <div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
60
      <h2>해당 방에 대한 참여코드는 {props.roomCode} 입니다.</h2>
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
61
      {/* 상대방이 보낸 메세지 띄우기 + 같은유저면 프로필 이미지는 생략(chat을 object로 보낸사람과 함께 보내서 구분하자) */}
62
63
64
65
66
67
68
69
70
71
72
73
74
75
      {chat.map((value, index) => {
        if (!(value == '')) {
          return (
            <Row key={index} className='m-1 ml-3' >
              <Col xs={2}>
                {user.profileimg ? <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "50px", height: "50px" }} roundedCircle /> : <Image src='https://www.flaticon.com/svg/vstatic/svg/149/149071.svg?token=exp=1610922596~hmac=f4b972b9db509d4e3cc2eb40543b0b0f' style={{ width: "50px", height: "50px" }} roundedCircle />}
              </Col>
              <Col xs={8}>
                <Row><strong>{user.nickname} {index}</strong></Row>
                <Row className='d-flex flex-wrap-nowrap'>
                  <Col className='border border-dark' style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'white', borderRadius: '5px', fontSize: 'x-large' }}>{value}</Col>
                  <Col className='ml-4'>{new Date().toLocaleTimeString()}</Col>
                </Row>
              </Col>
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
76
            </Row>
77
78
79
80
81
          )
        } else {
          return null
        }
      })
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
82
83
      }
      {/* 내가 보낸 메세지 띄우기 */}
84
85
86
87
88
89
90
91
92
93
      {chat.map((value, index) => {
        if (!(value == '')) {
          return (
            <Row key={index} className='m-1 mr-4 justify-content-end'>
              <div className='d-flex flex-wrap-nowrap' >
                <Row className='mr-4'>{time}</Row>
                <Row style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value}</Row>
              </div>
            </Row>
          )
Soo Hyun Kim's avatar
Soo Hyun Kim committed
94
95
96
        } else {
          return null
        }
97
      })
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
98
99
100
101
      }



102
103


우지원's avatar
ul    
우지원 committed
104
      <Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
105
      <Form onSubmit={sendMsgCH}>
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
106
107
108
109
110
        <Form.Group className='d-flex flex-wrap-nowrap justify-content-center ml-2 mr-2'>
          <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%' }} />
          <Button variant="warning" type="submit" disabled={disabled} style={{ width: '10%' }}>
            전송
          </Button>
우지원's avatar
ul    
우지원 committed
111
        </Form.Group>
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
112

113
      </Form>
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
114
    </div >
우지원's avatar
ul    
우지원 committed
115
116
117
118
119


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
120

우지원's avatar
ul    
우지원 committed
121
export default Chat;