11import { useAuthStore } from '@/domains/shared/store/auth' ;
22import { useToast } from '@/shared/components/toast/useToast' ;
33import { useCallback } from 'react' ;
4+ import { useEffect , useState } from 'react' ;
5+ import { usePathname , useRouter } from 'next/navigation' ;
6+ import { getCookie , removeCookie } from '@/domains/shared/auth/utils/cookie' ;
47
58export const useLogout = ( ) => {
69 const logout = useAuthStore ( ( state ) => state . logout ) ;
@@ -18,3 +21,55 @@ export const useLogout = () => {
1821
1922 return handleLogout ;
2023} ;
24+
25+ export const useLoginRedirect = ( ) => {
26+ const router = useRouter ( ) ;
27+ const pathname = usePathname ( ) ;
28+ const { user, updateUser } = useAuthStore ( ) ;
29+ const { toastSuccess } = useToast ( ) ;
30+
31+ const [ loading , setLoading ] = useState ( true ) ;
32+ const [ welcomeModalOpen , setWelcomeModalOpen ] = useState ( false ) ;
33+
34+ useEffect ( ( ) => {
35+ if ( ! user && loading ) {
36+ updateUser ( )
37+ . then ( ( fetchedUser ) => {
38+ if ( ! fetchedUser ) router . replace ( '/login' ) ;
39+ } )
40+ . catch ( ( ) => router . replace ( '/login' ) )
41+ . finally ( ( ) => setLoading ( false ) ) ;
42+ } else {
43+ setLoading ( false ) ;
44+ }
45+ } , [ user , loading , updateUser , router ] ) ;
46+
47+ useEffect ( ( ) => {
48+ if ( ! user || loading ) return ;
49+
50+ const preLoginPath = getCookie ( 'preLoginPath' ) || '/' ;
51+
52+ if ( user && preLoginPath === '/login' ) {
53+ router . replace ( '/' ) ;
54+ removeCookie ( 'preLoginPath' ) ;
55+ return ;
56+ }
57+
58+ if ( pathname . startsWith ( '/login/user/first-user' ) ) {
59+ setWelcomeModalOpen ( true ) ;
60+ } else if ( pathname . startsWith ( '/login/user/success' ) ) {
61+ toastSuccess ( `${ user . nickname } 님 \n 로그인 성공 🎉` ) ;
62+ router . replace ( preLoginPath ) ;
63+ removeCookie ( 'preLoginPath' ) ;
64+ }
65+ } , [ pathname , user , loading , router , toastSuccess ] ) ;
66+
67+ const handleCloseWelcomeModal = ( ) => {
68+ setWelcomeModalOpen ( false ) ;
69+ const preLoginPath = getCookie ( 'preLoginPath' ) || '/' ;
70+ removeCookie ( 'preLoginPath' ) ;
71+ router . replace ( preLoginPath ) ;
72+ } ;
73+
74+ return { loading, welcomeModalOpen, handleCloseWelcomeModal, user } ;
75+ } ;
0 commit comments