React 실시간 채팅, realtimebase에서 firestore로 바꾼 이유(feat. firebase)

김민우·2023년 2월 16일
0

스파르타 내배캠4기

목록 보기
66/73

💻💻 실시간 채팅 기능을 맡게 되어 구글링도 해보고, 유튜브도 검색해 본 결과 많은 분들이 FireBase의 realtimebase를 이용해서 실시간 채팅을 구현한 것을 볼 수 있었다.

하지만 내가 realtimebase에서 firestore로 바꾼 이유는 이것이다.

1. 대부분 옛날 글들이었다.

2. firebase 문서에서도 realtimebase보다 firestore에 대해 더 자세하게 나와있다.

3. 비교적 최신버전이다.

4. 용량도 훨씬 크게 사용할 수 있다.

5. collection 관리를 쉽게 할 수 있다

메시지 전송 📣📣

        <ChatFormSection>
          <ChatInputBody>
            <ChatInput
              type="text"
              value={content}
              onChange={handleChange}
              onKeyPress={EnterKeyPress}
            />
            <ChatBtn onClick={handleSubmit}>
              <SendBtn>전송</SendBtn>
            </ChatBtn>
          </ChatInputBody>
        </ChatFormSection>
  // 메세지 데이터 올리기
  const handleSubmit = async () => {
    if (content !== '') {
      await updateDoc(doc(db, 'teamChat', teamLocationID), {
        message: [
          ...chatInfo,
          {
            comment: content,
            uid: authService.currentUser.uid,
            profileImg: chatUserImage,
            nickName: authService.currentUser.displayName,
          },
        ],
      });
    }
    setContent('');
  };

메시지 화면에 보여주기 🔔🔔

        <ContentChatArea>
          <MessageBox key={v4()} t={AddMessage} />
          <div ref={scrollRef} />
        </ContentChatArea>

메시지 데이터 받아오기

  // 기존 채팅 내용
  const [chatInfo, setChatInfo] = useState([]);
  const [AddMessage, setAddtMessage] = useState([]);

  const getChatID = () => {
    const q = query(
      collection(db, 'teamChat'),
      where('teamID', '==', teamLocationID),
    );
    const unsubscribe = onSnapshot(q, (snapshot) => {
      const newInfo = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      setChatInfo(newInfo[0]?.message);
      setAddtMessage(newInfo[0]?.message);
    });

    return unsubscribe;
  };


화면에 보여주기

const MessageBox = ({ t }) => {
  // 나의 채팅
  const myChat = t.filter((a) => a.uid === authService.currentUser.uid);

  // 상대방 채팅
  const otherChat = t.filter((a) => a.uid !== authService.currentUser.uid);

  return (
    <>
      {otherChat.map((data) => {
        return (
          <MessageSection key={v4()}>
            <MessageImageBox>
              <MessageImage src={data.profileImg} alt="" />
            </MessageImageBox>
            <MessageTextBox>
              <MessageNickName>{data.nickName}</MessageNickName>
              <MessageContent>{data.comment}</MessageContent>
            </MessageTextBox>
          </MessageSection>
        );
      })}
      {myChat.map((data) => {
        return (
          <MyMessageSection key={v4()}>
            <MyMessageTextBox>
              <MyMessageNickName>{data.nickName}</MyMessageNickName>
              <MyMessageContent>{data.comment}</MyMessageContent>
            </MyMessageTextBox>
            <MyMessageImageBox>
              <MyMessageImage src={data.profileImg} />
            </MyMessageImageBox>
          </MyMessageSection>
        );
      })}
    </>
  );
};

export default MessageBox;
profile
개발자로서 한걸음

0개의 댓글