@@ -13,6 +13,7 @@ export interface User {
1313interface AuthState {
1414 user : User | null ;
1515 isLoggedIn : boolean ;
16+ isAuthChecked : boolean ;
1617 setUser : ( user : User ) => void ;
1718 logout : ( ) => Promise < void > ;
1819 loginWithProvider : ( provider : User [ 'provider' ] ) => void ;
@@ -21,9 +22,12 @@ interface AuthState {
2122 checkAuth : ( ) => Promise < User | null > ;
2223}
2324
25+ const hasAccessToken = typeof document !== 'undefined' && document . cookie . includes ( 'accessToken' ) ;
26+
2427export const useAuthStore = create < AuthState > ( ) ( ( set ) => ( {
2528 user : null ,
26- isLoggedIn : false ,
29+ isLoggedIn : hasAccessToken ,
30+ isAuthChecked : false ,
2731
2832 loginWithProvider : ( provider ) => {
2933 window . location . href = `${ getApi } /oauth2/authorization/${ provider } ` ;
@@ -41,11 +45,12 @@ export const useAuthStore = create<AuthState>()((set) => ({
4145 method : 'POST' ,
4246 credentials : 'include' ,
4347 } ) ;
44- set ( { user : null , isLoggedIn : false } ) ;
48+
49+ // 상태 초기화
50+ set ( { user : null , isLoggedIn : false , isAuthChecked : true } ) ;
4551 } catch ( err ) {
4652 console . error ( '로그아웃 실패' , err ) ;
47- } finally {
48- set ( { user : null , isLoggedIn : false } ) ;
53+ set ( { user : null , isLoggedIn : false , isAuthChecked : true } ) ;
4954 }
5055 } ,
5156
@@ -75,25 +80,21 @@ export const useAuthStore = create<AuthState>()((set) => ({
7580 }
7681 } ,
7782
78- // 시작 시 로그인 상태 확인
7983 checkAuth : async ( ) => {
84+ const state = useAuthStore . getState ( ) ;
85+ if ( ! state . isLoggedIn || state . isAuthChecked ) return null ;
86+
8087 try {
81- const res = await fetch ( `${ getApi } /user/auth/me` , {
82- method : 'GET' ,
83- credentials : 'include' ,
84- } ) ;
85- if ( ! res . ok ) throw new Error ( '인증 실패' ) ;
88+ const res = await fetch ( `${ getApi } /user/auth/me` , { method : 'GET' , credentials : 'include' } ) ;
89+ if ( ! res . ok ) return set ( { user : null , isLoggedIn : false } ) ;
8690
8791 const data = await res . json ( ) ;
8892 const userInfo = data ?. data ?. user ;
89- if ( userInfo ) {
90- set ( { user : userInfo , isLoggedIn : true } ) ;
91- return userInfo ;
92- }
93- return null ;
94- } catch {
95- set ( { user : null , isLoggedIn : false } ) ;
96- return null ;
93+ if ( userInfo ) set ( { user : userInfo , isLoggedIn : true } ) ;
94+
95+ return userInfo || null ;
96+ } finally {
97+ set ( { isAuthChecked : true } ) ;
9798 }
9899 } ,
99100} ) ) ;
0 commit comments