|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect, useState } from 'react'; |
| 4 | +import { usePathname, useRouter } from 'next/navigation'; |
| 5 | +import { useAuthStore } from '@/shared/@store/auth'; |
| 6 | +import { useModalStore } from '@/shared/@store/modal'; |
| 7 | +import { customToast } from '@/shared/components/toast/CustomToastUtils'; |
| 8 | +import Spinner from '../spinner/Spinner'; |
| 9 | + |
| 10 | +function LoginRedirectHandler() { |
| 11 | + const pathname = usePathname(); |
| 12 | + const router = useRouter(); |
| 13 | + const { user, updateUser } = useAuthStore(); |
| 14 | + const { openWelcomeModal } = useModalStore(); |
| 15 | + const [loading, setLoading] = useState(true); |
| 16 | + |
| 17 | + useEffect(() => { |
| 18 | + if (!user && loading) { |
| 19 | + updateUser() |
| 20 | + .then((fetchedUser) => { |
| 21 | + if (!fetchedUser) { |
| 22 | + router.replace('/login'); |
| 23 | + } |
| 24 | + }) |
| 25 | + .catch(() => { |
| 26 | + router.replace('/login'); |
| 27 | + }) |
| 28 | + .finally(() => setLoading(false)); |
| 29 | + } |
| 30 | + }, [user, loading, updateUser, router]); |
| 31 | + |
| 32 | + useEffect(() => { |
| 33 | + if (!user || loading) return; |
| 34 | + |
| 35 | + const preLoginPath = sessionStorage.getItem('preLoginPath') || '/'; |
| 36 | + |
| 37 | + if (pathname.startsWith('/login/first-user')) { |
| 38 | + openWelcomeModal(user.nickname); |
| 39 | + } else if (pathname.startsWith('/login/success')) { |
| 40 | + customToast.success(`${user.nickname}님 \n 로그인 성공 🎉`); |
| 41 | + router.replace(preLoginPath); |
| 42 | + } |
| 43 | + }, [pathname, user, router, openWelcomeModal, loading]); |
| 44 | + |
| 45 | + if (loading) { |
| 46 | + return ( |
| 47 | + <div className="page-layout max-w-824 flex-center"> |
| 48 | + <Spinner /> |
| 49 | + </div> |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + return null; |
| 54 | +} |
| 55 | +export default LoginRedirectHandler; |
0 commit comments