-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
withAuth 함수를 정의하여 특정 페이지 진입시 auth 여부에 따라 분기 처리할 수 있도록 했다. 원하는 페이지 컴포넌트에 withAuth 함수를 씌워 export 하면 된다.한 가지 단점은 react hook을 사용하는 기능이기 때문에 해당 페이지를 client component로 선언해야 한다는 점이다. 또한, auth 관련 fetching 과정에서 loading 중인 state를 기록하기 위해 authInfo에 isLoading이란 속성을 추가했다.
- Loading branch information
Showing
5 changed files
with
49 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
'use client'; | ||
|
||
import { useRouter } from 'next/navigation'; | ||
import { useEffect } from 'react'; | ||
import { useAuthStore } from '@/stores/authStore'; | ||
|
||
export interface WithAuthProps {} // 추후에 인증 과정에 더 필요한 props를 위해 | ||
|
||
export default function withAuth<T extends WithAuthProps = WithAuthProps>( | ||
Component: React.ComponentType<T>, | ||
) { | ||
const ComponentWithAuth = (props: Omit<T, keyof WithAuthProps>) => { | ||
const isAuthorized = useAuthStore((state) => state.authInfo.isAuthorized); | ||
const isLoading = useAuthStore((state) => state.authInfo.isLoading); | ||
const router = useRouter(); | ||
|
||
useEffect(() => { | ||
// 가장 초기 상태에는 undefined이므로, 해당 경우를 고려 해주어야 함 | ||
if (isLoading !== undefined && !isLoading && !isAuthorized) { | ||
router.push('/login'); | ||
} | ||
}); | ||
|
||
return !isLoading && isAuthorized ? ( | ||
<Component {...(props as T)} /> | ||
) : ( | ||
<div className="">loading</div> // 렌더링과 라우팅 사이의 딜레이 시 보여질 화면 | ||
); | ||
}; | ||
|
||
return ComponentWithAuth; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters