Chat.js 4.24 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

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

JeongYeonwoo's avatar
JeongYeonwoo committed
10
11
  const [sender, setSender] = useState([])

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
12
  const [inner, setInner] = useState([''])
Soo Hyun Kim's avatar
Soo Hyun Kim committed
13
  const [chat, setChat] = useState([])   //object로 key는 보낸사람 value는 메세지
JeongYeonwoo's avatar
JeongYeonwoo committed
14
15
16

  const [img, setImg] = useState([])

JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
17
  const [disabled, setDisabled] = useState(true)
Choi Ga Young's avatar
Choi Ga Young committed
18
19
  const [user, setUser] = useState('')
  const [error, setError] = useState('');
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
20
21
22
23
24
25
26
27
28
29
30

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

31
32
  function handleChange(e) {
    e.preventDefault()
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
33
    setInner(e.target.value)
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
34
    setDisabled(false)
35
36
37
  }

  function sendMsgCH(e) {
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
38
    e.preventDefault()
JeongYeonwoo's avatar
JeongYeonwoo committed
39

JeongYeonwoo's avatar
JeongYeonwoo committed
40
41
42
    props.setSingleImg(user.profileimg)
    props.setSingleUser(user.nickname)
    // props.setSingleUser(sessionStorage.getItem('name'))
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
43
    props.setSingleChat(inner)
JeongYeonwoo's avatar
JeongYeonwoo committed
44

45
    props.sendMsg(e)
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
46
    setInner('')
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
47
    setDisabled(true)
48
  }
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
49
50
51
  useEffect(() => {
    getProfile(userId)
  }, [userId])
52

Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
53
  useEffect(() => {
JeongYeonwoo's avatar
JeongYeonwoo committed
54
    setImg([...img, props.singleImg])
JeongYeonwoo's avatar
JeongYeonwoo committed
55
    setSender([...sender, props.singleUser])
Soo Hyun Kim's avatar
soo0115    
Soo Hyun Kim committed
56
    setChat([...chat, props.singleChat])
JeongYeonwoo's avatar
JeongYeonwoo committed
57
  }, [props.singleChat])
JeongYeonwoo's avatar
yeonwoo    
JeongYeonwoo committed
58

JeongYeonwoo's avatar
JeongYeonwoo committed
59
  useEffect(() => {
JeongYeonwoo's avatar
JeongYeonwoo committed
60
    setImg([...img, props.recievedImg])
JeongYeonwoo's avatar
JeongYeonwoo committed
61
    setSender([...sender, props.recievedUser])
JeongYeonwoo's avatar
JeongYeonwoo committed
62
    setChat([...chat, props.recievedMsg])
JeongYeonwoo's avatar
JeongYeonwoo committed
63
  }, [props.recievedMsg])
Choi Ga Young's avatar
aa    
Choi Ga Young committed
64

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

JeongYeonwoo's avatar
JeongYeonwoo committed
104
105
106
107
108
109
110
111
112
113
114
115
116
        <Button variant="light" onClick={props.handleChatc} >{`<`}</Button>


      </Container >
        <Form onSubmit={sendMsgCH} fluid>
          <Form.Group className='d-flex flex-wrap-nowrap justify-content-center m-3'>
            <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>
          </Form.Group>
        </Form>
    </>
우지원's avatar
ul    
우지원 committed
117
118
119
120
121


  );
}

Soo Hyun Kim's avatar
Soo Hyun Kim committed
122

우지원's avatar
ul    
우지원 committed
123
export default Chat;
JeongYeonwoo's avatar
JeongYeonwoo committed
124