Vue3, Firebase 프로젝트 - 채팅앱 VSignal

9. Vue3 Firebase 프로젝트 채팅앱 VSignal - 상대방이 온라인인지 확인

그랜파 개발자 2025. 3. 19. 04:11

🔥 1:1 채팅에서 상대방의 온라인 상태 표시 UI 추가

 

1:1 채팅에서 상대방의 온라인 상태를 실시간으로 감지하고,
UI에서 실시간으로 상태 업데이트를 반영하여
상대방이 온라인 또는 오프라인 상태를 표시할 수 있습니다.

1. 상대방 온라인 상태 가져오기

1:1 채팅에서는 현재 채팅 중인 상대방의 온라인 상태만 표시하면 돼.
현재 채팅방의 상대방 uid를 가져와서 Realtime Database에서 온라인 상태를 확인하자.

2. 상대방 상태 가져오는 Store 함수 추가

📌 store/userStore.js 수정

import { defineStore } from "pinia";
import { getDatabase, ref, onValue } from "firebase/database";

export const useUserStore = defineStore("user", {
  state: () => ({
    onlineUsers: {}, // 전체 온라인 유저 정보
    currentChatUserStatus: "offline", // 현재 채팅 상대방의 상태
  }),

  actions: {
    // ✅ 전체 온라인 유저 감지
    listenForOnlineUsers() {
      const db = getDatabase();
      const onlineRef = ref(db, "users");

      onValue(onlineRef, (snapshot) => {
        if (snapshot.exists()) {
          this.onlineUsers = snapshot.val();
        }
      });
    },

    // ✅ 특정 사용자 온라인 상태 감지 (1:1 채팅용)
    listenForUserStatus(userId) {
      if (!userId) return;
      const db = getDatabase();
      const userRef = ref(db, `users/${userId}/status`);

      onValue(userRef, (snapshot) => {
        if (snapshot.exists()) {
          this.currentChatUserStatus = snapshot.val();
        } else {
          this.currentChatUserStatus = "offline";
        }
      });
    },
  },
});

✔ listenForUserStatus(userId) → 1:1 채팅에서 상대방의 온라인 상태를 가져옴
✔ currentChatUserStatus → 현재 1:1 채팅 상대방의 상태를 저장

3. 1:1 채팅 화면에서 상대방 상태 표시

📌 ChatRoom.vue 수정

<script setup>
import { useUserStore } from "@/store/userStore";
import { useRoute } from "vue-router";
import { onMounted } from "vue";

const userStore = useUserStore();
const route = useRoute();
const chatUserId = route.params.userId; // URL에서 상대방 userId 가져오기

onMounted(() => {
  userStore.listenForUserStatus(chatUserId); // ✅ 상대방 온라인 상태 감지
});
</script>

<template>
  <v-card>
    <v-card-title>
      상대방 상태:
      <v-icon :color="userStore.currentChatUserStatus === 'online' ? 'green' : 'grey'">
        mdi-circle
      </v-icon>
      {{ userStore.currentChatUserStatus === "online" ? "온라인" : "오프라인" }}
    </v-card-title>

    <v-divider></v-divider>

    <v-card-text>
      <!-- 채팅 메시지 영역 -->
    </v-card-text>
  </v-card>
</template>

✅ 상대방이 "online"이면 초록색 🟢
✅ 상대방이 "offline"이면 회색 ⚫
✅ 실시간으로 상대방 상태가 바뀌면 자동 반영! 🚀

🎯 결론

✅ 1:1 채팅에서 상대방의 온라인 상태를 실시간으로 감지
✅ 상대방이 온라인이면 초록색 아이콘, 오프라인이면 회색 아이콘 표시
✅ UI에서 실시간으로 상태 업데이트 반영!