Skip to content

Commit

Permalink
usercontext & authcontext 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
ipcgrdn committed Jan 14, 2025
1 parent 068f54b commit 1e72f69
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 21 deletions.
20 changes: 14 additions & 6 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { getAuthCookie } from "@/lib/server-auth";
import { ThemeProvider } from "@/contexts/theme/ThemeContext";
import { UserProvider } from "@/contexts/auth/UserContext";

// getUser를 layout 레벨에서 캐싱
// getUser 함수 수정
const getUser = async () => {
const accessToken = getAuthCookie();

Expand All @@ -25,8 +25,14 @@ const getUser = async () => {
credentials: "include",
});

if (!response.ok) return null;
return response.json();
if (!response.ok) {
console.error('Failed to fetch user:', response.status);
return null;
}

// response.json() 한 번만 호출
const userData = await response.json();
return userData;
} catch (error) {
console.error('Failed to fetch user:', error);
return null;
Expand All @@ -51,14 +57,16 @@ export default async function RootLayout({
}: {
children: React.ReactNode;
}) {
const user = await getUser();
// 초기 유저 정보 가져오기
const initialUser = await getUser();
const isAuthenticated = !!initialUser;

return (
<html lang="ko" suppressHydrationWarning>
<body>
<ThemeProvider>
<AuthProvider>
<UserProvider initialUser={user}>
<AuthProvider initialAuth={isAuthenticated}>
<UserProvider initialUser={initialUser}>
<BackgroundImage />
<div className="relative min-h-screen w-full overflow-hidden">
<div className="fixed inset-0 backdrop-blur-[2px] bg-white/[0.01] dark:bg-transparent" />
Expand Down
4 changes: 2 additions & 2 deletions src/components/profile/AlbumList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ export function AlbumList({ albums }: AlbumListProps) {

{/* 앨범 정보 */}
<div className="space-y-2">
<h3 className="font-medium text-lg line-clamp-1 group-hover:text-black/50 transition-colors">
<h3 className="font-medium text-md line-clamp-1 group-hover:text-white/50 dark:group-hover:text-black/50 transition-colors">
{album.title}
</h3>
<div className="flex items-center gap-2 text-sm text-muted-foreground group-hover:text-black/50 transition-colors">
<div className="flex items-center gap-2 text-xs text-muted-foreground group-hover:text-white/50 dark:group-hover:text-black/50 transition-colors">
<Calendar className="w-4 h-4" />
<span>{formatDate(album.releaseDate)}</span>
</div>
Expand Down
34 changes: 30 additions & 4 deletions src/contexts/auth/AuthContext.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"use client";

import { createContext, useContext, useCallback, useMemo, useReducer } from "react";
import { createContext, useContext, useCallback, useMemo, useReducer, useEffect } from "react";
import { AuthContextType, AuthState } from "./types";
import { checkAuth } from "@/lib/auth";

const initialState: AuthState = {
isAuthenticated: false,
Expand Down Expand Up @@ -29,8 +30,32 @@ function authReducer(state: AuthState, action: AuthAction): AuthState {

const AuthContext = createContext<AuthContextType | null>(null);

export function AuthProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(authReducer, initialState);
interface AuthProviderProps {
children: React.ReactNode;
initialAuth: boolean;
}

export function AuthProvider({ children, initialAuth }: AuthProviderProps) {
const [state, dispatch] = useReducer(authReducer, {
...initialState,
isAuthenticated: initialAuth,
});

// 인증 상태 체크
const checkAuthStatus = useCallback(async () => {
try {
const { isAuthenticated } = await checkAuth();
dispatch({ type: "SET_AUTH", payload: isAuthenticated });
} catch (error) {
console.error('Auth check failed:', error);
dispatch({ type: "SET_AUTH", payload: false });
}
}, []);

// 초기 마운트 시 인증 상태 체크
useEffect(() => {
checkAuthStatus();
}, [checkAuthStatus]);

const login = useCallback(async () => {
dispatch({ type: "SET_LOADING", payload: true });
Expand Down Expand Up @@ -69,7 +94,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
...state,
login,
logout,
}), [state, login, logout]);
checkAuthStatus,
}), [state, login, logout, checkAuthStatus]);

return (
<AuthContext.Provider value={value}>
Expand Down
10 changes: 9 additions & 1 deletion src/contexts/auth/UserContext.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"use client";

import { createContext, useContext, useCallback, useMemo, useReducer } from "react";
import { createContext, useContext, useCallback, useMemo, useReducer, useEffect } from "react";
import { UserContextType, UserState, User } from "./types";
import { useAuth } from "./AuthContext";

type UserAction =
| { type: "SET_USER"; payload: User | null }
Expand All @@ -26,10 +27,17 @@ interface UserProviderProps {
}

export function UserProvider({ children, initialUser }: UserProviderProps) {
const { isAuthenticated } = useAuth();
const [state, dispatch] = useReducer(userReducer, {
user: initialUser,
});

useEffect(() => {
if (!isAuthenticated) {
dispatch({ type: "CLEAR_USER" });
}
}, [isAuthenticated]);

const updateUser = useCallback((user: User) => {
dispatch({ type: "SET_USER", payload: user });
}, []);
Expand Down
8 changes: 0 additions & 8 deletions src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,4 @@ export async function checkAuth() {
console.error('Error checking auth:', error);
return { isAuthenticated: false, accessToken: null };
}
}

// API 요청을 위한 헤더 생성 헬퍼 함수
export function getAuthHeaders(token: string) {
return {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
};
}

0 comments on commit 1e72f69

Please sign in to comment.