본문 바로가기

카테고리 없음

WelKo ( 마이 페이지 오류 해결 )

한 컴포넌트 내에서 같은 테이블을 참조하지만 불러오는 데이터의 양이 다르면서 불일치 발생

  const {
    data: reservationsData,
    error,
    isPending
  } = useQuery<
    (Tables<'payments'> & {
      users: { id: string };
      posts: {
        id: string;
        user_id: string | null;
        title: string;
        image: string | null;
        price: number | null;
        startDate: string | null;
        endDate: string | null;
      };
    })[]
  >({
    queryKey: ['reservations', userId],
    queryFn: () => fetchReservations(userId),
    enabled: !!userId
  });
  const handleChat = (post: Tables<'posts'>) => {
    const postAuthorId = post.user_id;
    const query = new URLSearchParams({
      postId: post.id,
      postTitle: post.title || '',
      postImage: post.image || ''
    }).toString();
    router.push(`/${userId}/${postAuthorId}/chatpage?${query}`);
  };

 

Partial<T> 사용:

만약 전체 타입이 필요한 경우, 일부 필드만 있을 수 있다는 점을 반영하기 위해 Partial<T>를 사용하여 타입을 유연하게 만듭니다.

const handleChat = (post: Partial<Tables<'posts'>>) => {
  const postAuthorId = post.user_id;
  const query = new URLSearchParams({
    postId: post.id || '',
    postTitle: post.title || '',
    postImage: post.image || ''
  }).toString();
  router.push(`/${userId}/${postAuthorId}/chatpage?${query}`);
};

post 객체의 필드가 선택적임을 의미합니다. 모든 필드가 반드시 존재하지 않아도 됩니다.

 

 

채팅 리스트 페이지에서 채팅 목록이 없을 시 무한 로딩 화면이 나오고 만들어둔 빈페이지UI가 안나오던 문제

  const {
    data: chatData,
    error: chatError,
    isPending: chatPending
  } = useQuery<Message[]>({
    queryKey: ['chatList', userId],
    queryFn: async () => {
      const response = await axios.get(API_MYPAGE_CHATS(userId));
      return response.data;
    },
    refetchInterval: 1000
  });

기존에는 1초마다 리패치를 통하다보니 pending상태가 계속 유지되던 부분이 문제였기 때문에

  const {
    data: chatData = [],
    error: chatError,
    isPending: chatPending
  } = useQuery<Message[]>({
    queryKey: ['chatList', userId],
    queryFn: async () => {
      const response = await axios.get(API_MYPAGE_CHATS(userId));
      return response.data;
    },
    refetchInterval: false
  });

위와 같이 기본값을 false로 설정 한 후

  useEffect(() => {
    if (chatData.length > 0 && !intervalId) {
      const id = setInterval(() => {
        queryClient.invalidateQueries({
          queryKey: ['chatList', userId]
        });
      }, 1000);
      setIntervalId(id);
    }

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [chatData, queryClient, userId, intervalId]);

useEffect를 통해 시간을 새롭게 설정 후 

  const {
    data: postData = [],
    error: postError,
    isPending: postPending
  } = useQuery<Post[]>({
    queryKey: ['postDetails', postIds],
    queryFn: async () => {
      const postDetails = await Promise.all(postIds.map((postId) => fetchPostDetails(postId)));
      return postDetails;
    },
    enabled: postIds.length > 0
  });

  const {
    data: userData = [],
    error: userError,
    isPending: userPending
  } = useQuery<User[]>({
    queryKey: ['userDetails', userIds],
    queryFn: async () => {
      const userDetails = await Promise.all(userIds.map((id) => fetchUserDetails(id)));
      return userDetails;
    },
    enabled: userIds.length > 0
  });

추가적으로 채팅 외에 필요한 투어 정보 및 유저 정보

  const {
    data: postData = [],
    error: postError,
    isPending: postPending
  } = useQuery<Post[]>({
    queryKey: ['postDetails', postIds],
    queryFn: async () => {
      const postDetails = await Promise.all(postIds.map((postId) => fetchPostDetails(postId)));
      return postDetails;
    }
  });

  const {
    data: userData = [],
    error: userError,
    isPending: userPending
  } = useQuery<User[]>({
    queryKey: ['userDetails', userIds],
    queryFn: async () => {
      const userDetails = await Promise.all(userIds.map((id) => fetchUserDetails(id)));
      return userDetails;
    }
  });

기존 enabled조건을 삭제하여 정상적으로 로딩 및 빈화면 구별 성공

 

 

빈 화면 스크롤 생기는 등 높이가 너무 큰 문제

 

h-screen을 min-h-[calc(100vh-400px)]로 대체하여 Tailwind CSS에서 특정 높이를 설정하기 위해 사용되는 방법을 활용

 

100vh는 뷰포트 높이(Viewport Height)의 100%를 의미합니다. 예를 들어, 브라우저 창의 높이가 800픽셀(px)이라면 100vh는 800px입니다.

따라서, calc(100vh - 400px)은 뷰포트 높이에서 400픽셀을 뺀 값을 통하여 UI구현

기존에는 스크롤이 존재
개선 이후 스크롤 사라지면서 UI 개선