Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/app/movers/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { dehydrate, HydrationBoundary, QueryClient } from "@tanstack/react-query

import { MoversPageView } from "@/components/mover/MoversPageView";
import { getMovers } from "@/lib/api/movers";
import { QUERY_KEYS } from "@/lib/constants/queryKeys";
import { getMoverListQueryKey, MOVER_LIST_GUEST_SCOPE } from "@/lib/constants/queryKeys";
import { parseMoversSearchParams, toMoversListQuery } from "@/lib/utils/moversSearchParams";

export const metadata: Metadata = {
Expand Down Expand Up @@ -31,7 +31,8 @@ export default async function MoversPage({ searchParams }: MoversPageProps) {
try {
// infinite query는 await 필수 (미대기 dehydrate 시 클라이언트 hydrate 깨질 수 있음)
await queryClient.prefetchInfiniteQuery({
queryKey: [...QUERY_KEYS.MOVERS.LIST, listQuery],
// 서버 prefetch에는 access token이 없으므로 guest 캐시로 분리합니다.
queryKey: getMoverListQueryKey(MOVER_LIST_GUEST_SCOPE, listQuery),
queryFn: ({ pageParam }) => getMovers({ ...listQuery, page: pageParam }),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
Expand Down
25 changes: 16 additions & 9 deletions src/components/mover/FavoriteMoversSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import Toast from "@/components/common/Toast/Toast";
import { Text } from "@/components/common/Text";
import MoverCard from "@/components/mover/MoverCard";
import { MoverCardSkeletonList } from "@/components/mover/MoverCardSkeleton";
import { useCustomerAuthReady } from "@/hooks/useCustomerAuthReady";
import { useFavoriteMovers } from "@/hooks/useFavoriteMovers";
import { useIsClient } from "@/hooks/useIsClient";
import { ChevronRightThinIcon } from "@/icons";
import { FAVORITE_MOVERS_SIDEBAR_LIMIT } from "@/lib/api/favorites";
import { getLoginRedirectPath, hasAuthSession } from "@/lib/auth/session";
import { getLoginRedirectPath } from "@/lib/auth/session";
import { APP_ROUTES } from "@/lib/constants/appRoutes";
import { mapMoverListItemToMover } from "@/lib/utils/mapMover";
import { cn } from "@/lib/utils/cn";
Expand Down Expand Up @@ -77,20 +77,27 @@ function FavoriteMoversSidebarStatus({
}

export function FavoriteMoversSidebar() {
// SSR/하이드레이션 전에는 토큰을 읽지 않아 서버·클라이언트 HTML을 동일하게 맞춤
const isClient = useIsClient();
const isLoggedIn = isClient && hasAuthSession();
const {
isPending: isAuthPending,
isAuthenticated,
isMover,
canFetch: isCustomerLoggedIn,
} = useCustomerAuthReady();
const query = useFavoriteMovers({
enabled: isLoggedIn,
enabled: isCustomerLoggedIn,
limit: FAVORITE_MOVERS_SIDEBAR_LIMIT,
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const [toastMessage, setToastMessage] = useState<string | null>(null);

if (!isAuthPending && isAuthenticated && isMover) {
return null;
}

const movers =
query.data?.data.map(mapMoverListItemToMover).slice(0, FAVORITE_MOVERS_SIDEBAR_LIMIT) ?? [];
const showSkeleton = !isClient || (isLoggedIn && query.isPending);
const showSkeleton = isAuthPending || (isCustomerLoggedIn && query.isPending);
// 찜한 기사님이 1명 이상일 때부터 더보기 표시, 비로그인·빈 목록에서는 숨김
const showMoreLink = isLoggedIn && !query.isError && movers.length > 0;
const showMoreLink = isCustomerLoggedIn && !query.isError && movers.length > 0;

return (
<aside className="hidden w-full flex-col gap-16 lg:flex lg:w-[327px] lg:shrink-0 lg:self-stretch lg:pt-[192px]">
Expand All @@ -117,7 +124,7 @@ export function FavoriteMoversSidebar() {
count={FAVORITE_MOVERS_SKELETON_COUNT}
label="찜한 기사님을 불러오는 중"
/>
) : !isLoggedIn ? (
) : !isCustomerLoggedIn ? (
<FavoriteMoversSidebarStatus
title="아직 로그인하지 않았어요"
description={
Expand Down
12 changes: 10 additions & 2 deletions src/components/mover/MoversList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import MoversErrorPanel from "@/components/mover/MoversErrorPanel";
import { useMovers } from "@/hooks/useMovers";
import { mapMoverListItemToMover } from "@/lib/utils/mapMover";
import type { MoversSearchParamsState } from "@/lib/utils/moversSearchParams";
import { useAuthStore } from "@/stores/useAuthStore";

interface MoversListProps {
filters: MoversSearchParamsState;
Expand All @@ -30,13 +31,20 @@ const MOVERS_NEXT_PAGE_SKELETON_COUNT = 2;

export function MoversList({ filters }: MoversListProps) {
const query = useMovers(filters);
const hasHydrated = useAuthStore((state) => state.hasHydrated);
const isCheckingAuth = useAuthStore((state) => state.isCheckingAuth);
const isAuthPending = !hasHydrated || isCheckingAuth;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const sentinelRef = useRef<HTMLDivElement>(null);
const { hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage, refetch } = query;
const [toastMessage, setToastMessage] = useState<string | null>(null);

const movers = query.data?.pages.flatMap((page) => page.data).map(mapMoverListItemToMover) ?? [];

useEffect(() => {
if (isAuthPending) {
return;
}

const sentinel = sentinelRef.current;
if (!sentinel) {
return;
Expand All @@ -55,9 +63,9 @@ export function MoversList({ filters }: MoversListProps) {

observer.observe(sentinel);
return () => observer.disconnect();
}, [hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);
}, [isAuthPending, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);

if (query.isPending) {
if (isAuthPending || query.isPending) {
return (
<MoverCardSkeletonList
variant="full"
Expand Down
33 changes: 33 additions & 0 deletions src/hooks/useAuthQueryCacheReset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"use client";

import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef } from "react";

import { useAuthStore } from "@/stores/useAuthStore";

const GUEST_SESSION_KEY = "guest";

/** 로그인·로그아웃·계정 전환 시 이전 사용자의 React Query 캐시를 제거합니다. */
export function useAuthQueryCacheReset() {
const queryClient = useQueryClient();
const isCheckingAuth = useAuthStore((state) => state.isCheckingAuth);
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
const userId = useAuthStore((state) => state.user?.id);
const previousSessionKeyRef = useRef<string | null>(null);

useEffect(() => {
if (isCheckingAuth) {
return;
}

const sessionKey = isAuthenticated && userId ? `user:${userId}` : GUEST_SESSION_KEY;
const previousSessionKey = previousSessionKeyRef.current;

// 최초 인증 확정 시에는 SSR prefetch 캐시를 유지하고, 이후 세션 전환만 정리합니다.
if (previousSessionKey !== null && previousSessionKey !== sessionKey) {
queryClient.clear();
}

previousSessionKeyRef.current = sessionKey;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}, [isAuthenticated, isCheckingAuth, queryClient, userId]);
}
23 changes: 15 additions & 8 deletions src/hooks/useMovers.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,33 @@
"use client";

import { getMovers } from "@/lib/api/movers";
import { hasAuthSession } from "@/lib/auth/session";
import { QUERY_KEYS } from "@/lib/constants/queryKeys";
import { getMoverListAuthScope, getMoverListQueryKey } from "@/lib/constants/queryKeys";
import { getAccessTokenPayload } from "@/lib/auth/accessTokenPayload";
import { getAccessToken } from "@/lib/auth/token";
import { toMoversListQuery, type MoversSearchParamsState } from "@/lib/utils/moversSearchParams";
import { useApiInfiniteQuery } from "@/hooks/queries/useApiInfiniteQuery";
import { useIsClient } from "@/hooks/useIsClient";
import { useAuthStore } from "@/stores/useAuthStore";

const MOVERS_LIST_STALE_TIME_MS = 60 * 1000;

export function useMovers(filters: MoversSearchParamsState) {
const listQuery = toMoversListQuery(filters);
const isClient = useIsClient();
// SSR prefetch는 서버에 access token이 없어 비회원 응답일 수 있음 → 로그인 시 즉시 재검증
const staleTime = isClient && hasAuthSession() ? 0 : MOVERS_LIST_STALE_TIME_MS;
const hasHydrated = useAuthStore((state) => state.hasHydrated);
const isCheckingAuth = useAuthStore((state) => state.isCheckingAuth);
const isAuthenticated = useAuthStore((state) => state.isAuthenticated);
const userId = useAuthStore((state) => state.user?.id);
const isAuthReady = hasHydrated && !isCheckingAuth;
const tokenUserId = isAuthenticated ? getAccessTokenPayload(getAccessToken() ?? "").userId : null;
const authScope = getMoverListAuthScope(userId ?? tokenUserId);

return useApiInfiniteQuery({
queryKey: [...QUERY_KEYS.MOVERS.LIST, listQuery],
queryKey: getMoverListQueryKey(authScope, listQuery),
queryFn: ({ pageParam }) => getMovers({ ...listQuery, page: pageParam }),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.pagination.hasNext ? lastPage.pagination.page + 1 : undefined,
staleTime,
enabled: isAuthReady,
// 로그인 응답의 isFavorite는 세션 복구 직후 항상 서버에서 다시 확인합니다.
staleTime: isAuthenticated ? 0 : MOVERS_LIST_STALE_TIME_MS,
});
}
12 changes: 12 additions & 0 deletions src/lib/constants/queryKeys.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
import type { MoversListQuery } from "@/types/mover";

export const MOVER_LIST_GUEST_SCOPE = "guest" as const;

export const getMoverListAuthScope = (userId?: string | null) =>
userId ? (`user:${userId}` as const) : MOVER_LIST_GUEST_SCOPE;

export const getMoverListQueryKey = (
authScope: ReturnType<typeof getMoverListAuthScope>,
query: Omit<MoversListQuery, "page">,
) => [...QUERY_KEYS.MOVERS.LIST, authScope, query] as const;

export const QUERY_KEYS = {
AUTH: {
ME: ["auth", "me"],
Expand Down
4 changes: 3 additions & 1 deletion src/providers/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
import { type ReactNode } from "react";

import { useAuthInit } from "@/hooks/useAuthInit";
import { useAuthQueryCacheReset } from "@/hooks/useAuthQueryCacheReset";

interface AuthProviderProps {
children: ReactNode;
}

/** 세션 초기화·만료 리스너만 담당. 상태는 useAuthStore를 구독합니다. */
/** 세션 초기화·만료 리스너와 사용자 전환 시 쿼리 캐시 정리를 담당합니다. */
export const AuthProvider = ({ children }: AuthProviderProps) => {
useAuthInit();
useAuthQueryCacheReset();
return children;
};