[TIL] 08/20 :: unReadcount

yeseul·2024년 8월 29일

<TIL>

목록 보기
36/43
  • 시연영상 찍기
  • useUser 커스텀훅에서 tanstackquery 버그 발생
    -> 로그인하면 유저정보 바로 안뜨고 새로고침 해야 뜨거나, 어쩔땐 또 바로 반영됨

* 문제발생

  • 헤더아이콘의 unReadcount 가 내가 안읽은 메세지 수가 아니라, 내가 보낸 메세지중에 상대가 안읽은 메세지 수가 반영됨
  • 유저정보 로그 찍어보니 undefined

* 원인

  • 로그인한 유저 정보가져오는 커스텀훅이 바뀜 -> 리턴값이 바뀜 -> 리턴데이터를 한번 더 타고 들어가야했음
  • user.id => user.user_id

* 해결

1. chatroomUtils 에서 안읽은 메세지 카운트하는 함수 수정
-> 구매자일때, 판매자일때 나누던 부분을 내가 아닌 상대가 보낸 메세지 필터로 통합시킴
-> user.user_id 로 변경
=> 리팩토링시 타입 수정해야함..

export const fetchUnreadCounts = async (
  user: any,
  chatrooms: any[],
  setUnreadCounts: (counts: { [key: string]: number }) => void
) => {
  const counts: { [key: string]: number } = {};

  for (const chatroom of chatrooms) {
    let data, error;

    // 내가 읽지 않은 메시지를 가져옴
    ({ data, error } = await supabase
      .from('Message')
      .select('is_read', { count: 'exact' })
      .eq('message_chatroom_id', chatroom.chatroom_id)
      .eq('is_read', false) // 읽지 않은 메시지 필터
      .neq('message_user_id', user.user_id)); // 상대방이 보낸 메시지 필터

    if (error) {
      console.error('읽지 않은 메세지 수 가져오는 중 에러발생', error);
    } else if (data) {
      counts[chatroom.chatroom_id] = data.length;
    }
  }
  setUnreadCounts(counts);
};

2. 의존성배열에 unReadCounts 추가

// HeaderIconBar

 const unreadCounts = unreadCountStore.getState().unreadCounts;
  // chatroomList가 업데이트되면 안 읽은 메시지 수를 계산
  useEffect(() => {
    const updateUnreadCounts = async () => {
      if (isLogin && chatroomList.length > 0) {
        const setUnreadCounts = unreadCountStore.getState().setUnreadCounts;
        await fetchUnreadCounts(userData, chatroomList, setUnreadCounts);
      }
    };

    updateUnreadCounts();
  }, [chatroomList, isLogin, userData, unreadCounts]);

* 수정해야할 부분

  • 상대가 보낸 메세지중에 내가 안읽은 메세지만 카운트에 반영되고, 읽으면 메세지 수 다시 줄어들게 반영 완료.
    ❗ 메세지가 올경우, 바로 unReadCount 가 반영되는게 아니라 새로고침하거나, 다른 페이지로 이동해야 반영된다.
  • 헤더에서 변화되는거라.. 변화를 계속 감지하고 있어야하는데, 성능고려하면 그게 효율적인지 잘 모르겠어서 고민해보고 리팩토링할때 수정해야겠음!

0개의 댓글