Commit 4f3330b3 authored by Soo Hyun Kim's avatar Soo Hyun Kim
Browse files

0121채팅창에이름코드

parent 35899ce6
...@@ -8,6 +8,7 @@ import catchErrors from '../utils/catchErrors'; ...@@ -8,6 +8,7 @@ import catchErrors from '../utils/catchErrors';
function Chat(props) { function Chat(props) {
// let defaultname = sessionStorage.getItem('name'); // let defaultname = sessionStorage.getItem('name');
const [roomName, setRoomName] = useState('')
const [inner, setInner] = useState(['']) const [inner, setInner] = useState([''])
const [chat, setChat] = useState([]) //object로 key는 보낸사람 value는 메세지 const [chat, setChat] = useState([]) //object로 key는 보낸사람 value는 메세지
const [disabled, setDisabled] = useState(true) const [disabled, setDisabled] = useState(true)
...@@ -24,6 +25,15 @@ function Chat(props) { ...@@ -24,6 +25,15 @@ function Chat(props) {
} }
} }
async function getRoomName(roomCode) {
try {
let res = await axios.get('/room/getRoomName', { params: { 'roomCode': roomCode } })
setRoomName(res.data)
} catch (error) {
catchErrors(error, setError)
}
}
function handleChange(e) { function handleChange(e) {
e.preventDefault() e.preventDefault()
setInner(e.target.value) setInner(e.target.value)
...@@ -54,6 +64,10 @@ function Chat(props) { ...@@ -54,6 +64,10 @@ function Chat(props) {
console.log('UseEffect recievechat', chat) console.log('UseEffect recievechat', chat)
}, [props.recievedMsg]) }, [props.recievedMsg])
useEffect(() => {
getRoomName(props.roomCode)
}, [props.roomCode])
// function check() { // function check() {
// // if (chat[chat.length-1].user ===chat[chat.length-2].user){ //마지막보낸거랑 그 전꺼랑 보낸사람이 같은지 비교 // // if (chat[chat.length-1].user ===chat[chat.length-2].user){ //마지막보낸거랑 그 전꺼랑 보낸사람이 같은지 비교
...@@ -67,51 +81,62 @@ function Chat(props) { ...@@ -67,51 +81,62 @@ function Chat(props) {
const time = new Date().toLocaleTimeString() const time = new Date().toLocaleTimeString()
return ( return (
<div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD", background: '' }}> <div className="chat" id="chat" style={{ border: "2px solid", height: "300%", margin: "1%", borderColor: "#BDBDBD", background: '' }}>
<h2>해당 방에 대한 참여코드는 {props.roomCode} 입니다.</h2> <Row class="d-flex justify-content-center" style={{ height: "80px", margin: "1%" }}>
<Col md="auto">
<Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
</Col>
<Col>
<Row style={{ fontSize: 'x-large' }}> {roomName} </Row>
<Row > {props.roomCode} </Row>
</Col>
</Row>
{/* <h2> 참여코드 : {props.roomCode} </h2> */}
{/* 상대방이 보낸 메세지 띄우기 + 같은유저면 프로필 이미지는 생략(chat을 object로 보낸사람과 함께 보내서 구분하자) */} {/* 상대방이 보낸 메세지 띄우기 + 같은유저면 프로필 이미지는 생략(chat을 object로 보낸사람과 함께 보내서 구분하자) */}
{chat.map((value, index) => { {
if (!(value == '')) { chat.map((value, index) => {
return ( if (!(value == '')) {
<Row key={index} className='m-1 ml-3' > return (
<Col xs={2}> <Row key={index} className='m-1 ml-3' >
{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 xs={2}>
</Col> {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 xs={8}> </Col>
<Row><strong>{user.nickname} {index}</strong></Row> <Col xs={8}>
<Row className='d-flex flex-wrap-nowrap'> <Row><strong>{user.nickname} {index}</strong></Row>
<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> <Row className='d-flex flex-wrap-nowrap'>
<Col className='ml-4'>{new Date().toLocaleTimeString()}</Col> <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>
</Row> <Col className='ml-4'>{new Date().toLocaleTimeString()}</Col>
</Col> </Row>
</Row> </Col>
) </Row>
} else { )
return null } else {
} return null
}) }
})
} }
{/* 내가 보낸 메세지 띄우기 */} {/* 내가 보낸 메세지 띄우기 */}
{chat.map((value, index) => { {
if (!(value == '')) { chat.map((value, index) => {
return ( if (!(value == '')) {
<Row key={index} className='m-1 mr-4 justify-content-end'> return (
<div className='d-flex flex-wrap-nowrap' > <Row key={index} className='m-1 mr-4 justify-content-end'>
<Row className='mr-4'>{time}</Row> <div className='d-flex flex-wrap-nowrap' >
<Row style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value}</Row> <Row className='mr-4'>{time}</Row>
</div> <Row style={{ width: 'max-content', maxWidth: '300px', height: 'auto', paddingLeft: '15px', paddingRight: '15px', background: 'yellow', borderRadius: '3px', fontSize: 'x-large' }}>{value}</Row>
</Row> </div>
) </Row>
} else { )
return null } else {
} return null
}) }
})
} }
<Button variant="light" onClick={props.handleChatc} >{`<`}</Button>
<Form onSubmit={sendMsgCH}> <Form onSubmit={sendMsgCH}>
<Form.Group className='d-flex flex-wrap-nowrap justify-content-center ml-2 mr-2'> <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%' }} /> <Form.Control className='border border-warning' name='chat' type="text" value={inner} onChange={handleChange} style={{ width: '85%' }} />
......
...@@ -8,7 +8,7 @@ function ClosedList(props) { ...@@ -8,7 +8,7 @@ function ClosedList(props) {
useEffect(() => { useEffect(() => {
getClosedList(); getClosedList();
}, []); }, [props.roomCode]);
async function getClosedList() { async function getClosedList() {
const userid = sessionStorage.getItem('userId') const userid = sessionStorage.getItem('userId')
...@@ -18,16 +18,16 @@ function ClosedList(props) { ...@@ -18,16 +18,16 @@ function ClosedList(props) {
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
const roomCode = e.target.name const roomCode = e.target.name
const roomName = e.target.value
props.enterChatRoom(roomCode) props.enterChatRoom(roomCode)
props.setRoomCode(roomCode) props.setRoomName(roomName)
} }
return ( return (
<div> <div>
{list.map((item, index) => {list.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}> <ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId} value={item.roomName}>
{item.roomName} {item.roomName}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
......
...@@ -7,7 +7,7 @@ function OpenList(props) { ...@@ -7,7 +7,7 @@ function OpenList(props) {
useEffect(() => { useEffect(() => {
getOpenList(); getOpenList();
}, []); }, [props.roomCode]);
async function getOpenList() { async function getOpenList() {
let res = await axios.get('/room/openlist') let res = await axios.get('/room/openlist')
...@@ -16,17 +16,15 @@ function OpenList(props) { ...@@ -16,17 +16,15 @@ function OpenList(props) {
function enterChatRoomCH(e) { function enterChatRoomCH(e) {
const roomCode = e.target.name const roomCode = e.target.code
props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함 props.enterChatRoom(roomCode) // 각각의 room으로 들어가도록 설정해야 함
props.setRoomCode(roomCode)
// props.clearChat()
} }
return ( return (
<div> <div>
{openlist.map((item, index) => {openlist.map((item, index) =>
<ListGroup key={index}> <ListGroup key={index}>
<ListGroup.Item action onClick={enterChatRoomCH} name={item.roomId}> <ListGroup.Item action onClick={enterChatRoomCH} code={item.roomId}>
{item.roomName} {item.roomName}
</ListGroup.Item> </ListGroup.Item>
</ListGroup> </ListGroup>
......
...@@ -34,6 +34,7 @@ function RoomMake(props) { ...@@ -34,6 +34,7 @@ function RoomMake(props) {
const Id = res.data.roomId const Id = res.data.roomId
alert(`방암호는 ${Id}입니다`) alert(`방암호는 ${Id}입니다`)
props.handleCloseModal() props.handleCloseModal()
props.handleChato()
setRoom(INIT_ROOM) setRoom(INIT_ROOM)
} catch (error){ } catch (error){
catchErrors(error, setError) catchErrors(error, setError)
......
...@@ -36,9 +36,10 @@ function Home() { ...@@ -36,9 +36,10 @@ function Home() {
//SOCKET 관련 시작 //SOCKET 관련 시작
function enterChatRoom(rName) { //방 입장하기 function enterChatRoom(rCode) { //방 입장하기
socket.emit('joinRoom', rName) socket.emit('joinRoom', rCode)
console.log(`joinRoom : ${rName} 입장`) setRoomCode(rCode)
console.log(`joinRoom : ${rCode} 입장`)
} }
const sendMsg = (e) => { const sendMsg = (e) => {
...@@ -70,10 +71,10 @@ function Home() { ...@@ -70,10 +71,10 @@ function Home() {
<Col className="list" md={5}> <Col className="list" md={5}>
<Tabs defaultActiveKey="closed" id="uncontrolled-tab-example"> <Tabs defaultActiveKey="closed" id="uncontrolled-tab-example">
<Tab eventKey="closed" title="내 채팅" onClick={handleChato} > <Tab eventKey="closed" title="내 채팅" onClick={handleChato} >
<ClosedList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} /> <ClosedList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode}/>
</Tab> </Tab>
<Tab eventKey="open" title="공개방" onClick={handleChato}> <Tab eventKey="open" title="공개방" onClick={handleChato}>
<OpenList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} /> <OpenList enterChatRoom={enterChatRoom} setRoomCode={setRoomCode} setRoomName={setRoomName} roomCode={roomCode}/>
</Tab> </Tab>
</Tabs> </Tabs>
</Col> </Col>
...@@ -91,8 +92,8 @@ function Home() { ...@@ -91,8 +92,8 @@ function Home() {
</div> </div>
</Col> </Col>
</Row> </Row>
<RoomMake showModal={showModal} handleCloseModal={handleCloseModal} /> <RoomMake showModal={showModal} handleCloseModal={handleCloseModal} handleChato={handleChato}/>
<EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} handleChato={handleChato} setRoomName={setRoomName}/> <EnterRoom showEnter={showEnter} enterChatRoom={enterChatRoom} handleCloseEnter={handleCloseEnter} handleChato={handleChato} setRoomCode={setRoomCode} setRoomName={setRoomName}/>
</> </>
); );
} }
......
...@@ -40,8 +40,8 @@ const makeRoom = async (req, res) => { ...@@ -40,8 +40,8 @@ const makeRoom = async (req, res) => {
const getClosedList = async (req, res) => { const getClosedList = async (req, res) => {
try { try {
console.log('req확인',req.query._id) console.log('req확인',req.query._id)
let list = await Room.find({ member: [req.query._id] }) let list = await Room.find({ member: req.query._id })
console.log('c_list가져오기', list.roomName) console.log('c_list가져오기', list.member)
return res.json(list) return res.json(list)
} catch (error) { } catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!') res.status(500).send('리스트 불러오기를 실패하였습니다!')
...@@ -58,6 +58,17 @@ const getOpenList = async (req, res) => { ...@@ -58,6 +58,17 @@ const getOpenList = async (req, res) => {
} }
} }
const getRoomName = async (req, res) => {
const roomId = req.query.roomCode
try {
let roominfo = await Room.findOne({ roomId: roomId }).select('roomName')
return res.json(roominfo.roomName)
} catch (error) {
res.status(500).send('리스트 불러오기를 실패하였습니다!')
}
}
const changemember = async (req, res) => { const changemember = async (req, res) => {
const { userId, roomId } = req.body const { userId, roomId } = req.body
console.log(roomId) console.log(roomId)
...@@ -76,4 +87,4 @@ const changemember = async (req, res) => { ...@@ -76,4 +87,4 @@ const changemember = async (req, res) => {
} }
} }
export default { makeRoom, getClosedList, getOpenList, changemember } export default { makeRoom, getClosedList, getOpenList, getRoomName, changemember }
...@@ -14,4 +14,7 @@ router.route('/room/openlist') ...@@ -14,4 +14,7 @@ router.route('/room/openlist')
router.route('/room/member') router.route('/room/member')
.put(roomCtrl.changemember) .put(roomCtrl.changemember)
router.route('/room/getRoomName')
.get(roomCtrl.getRoomName)
export default router export default router
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment