|
| 1 | +import { useAuthStore } from '@/domains/shared/store/auth'; |
| 2 | +import { useCallback } from 'react'; |
| 3 | +import { useEffect, useState } from 'react'; |
| 4 | +import { usePathname, useRouter } from 'next/navigation'; |
| 5 | +import { getCookie, removeCookie } from '@/domains/shared/auth/utils/cookie'; |
| 6 | +import { useToast } from '@/shared/hook/useToast'; |
| 7 | + |
| 8 | +export const useLogout = () => { |
| 9 | + const logout = useAuthStore((state) => state.logout); |
| 10 | + const { toastSuccess, toastError } = useToast(); |
| 11 | + |
| 12 | + const handleLogout = useCallback(async () => { |
| 13 | + try { |
| 14 | + await logout(); |
| 15 | + toastSuccess('로그아웃 되었습니다.'); |
| 16 | + } catch (err) { |
| 17 | + console.error('로그아웃 실패', err); |
| 18 | + toastError('로그아웃 실패 ❌ 다시 시도해주세요.'); |
| 19 | + } |
| 20 | + }, [logout, toastSuccess, toastError]); |
| 21 | + |
| 22 | + return handleLogout; |
| 23 | +}; |
| 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