Project/실시간 채팅 앱

오늘 한 작업들

CoderHan 2022. 9. 3. 18:07
반응형

오늘은 채팅방에 메세지를 보내는 기능을 추가했다.

빈문자열이나 null이라면 바로 return을 하게끔 해줬고

msg는 state에 있는걸 얕은복사로 가져와서 보낼 메세지를 추가한 뒤

setMessage로 업데이트 해주었다.

 

보낸 시간을 설정하면서 new Date함수를 다뤘는데 yyy-mm-dd hh-mm-ss형식으로 따로 뽑아주는 함수를 만들었다.

사람들은 yyyy-mm-dd도 쓰고 yy-mm-dd 등 다양한 형식을 쓸텐데 이를 활용해서 오픈소스로 만들어보면 좋겠다는 생각을 했다. 여유있을 때 해봐야겠다.

 

부가적으로 useEffect로 새로운 메세지가 전송되면 가장 하단으로 스크롤이 위치하게끔 만들었고, 엔터키로 메세지 전송하는 기능도 넣었다. 최대한 깔끔하게 코드를 작성하려고 노력하는 중인데, 우선은 기능구현이 먼저니 이를 완성한 뒤에

리팩토링을 거쳐야겠다.

    const sendMessage = () => {
        if(msgInputRef.current.value === null || msgInputRef.current.value === "") return

        const idx = messages.length
        const msg = [...messages];
        const sendMsg = { id : idx, sender : "han", sendTime : timeformat(new Date()), text : msgInputRef.current.value }
        msg.push(sendMsg);

        setMessage(msg);

        msgInputRef.current.value = ''
        msgInputRef.current.focus();
    }
 
    const onKeyPress = (e) => {
        if(e.key == 'Enter') {
            sendMessage()
        }
    }
 
    useEffect(() => {
        if (msgList.current) {
            msgList.current.scrollIntoView(
              {
                behavior: 'smooth',
                block: 'end',
                inline: 'nearest'
              })
          }
        })
반응형