|
3 | 3 | import AuthLoading from "@/components/auth/AuthLoading"; |
4 | 4 | import useAuthStore from "@/store/authStore"; |
5 | 5 | import { useRouter } from "next/navigation"; |
| 6 | +import { useEffect } from "react"; |
6 | 7 |
|
7 | 8 | const AuthNaverContainer = () => { |
8 | 9 | const router = useRouter(); |
9 | 10 | const authStore = useAuthStore(); |
10 | 11 |
|
11 | | - const url = new URL(window.location.href); |
12 | | - const naverLogin = async () => { |
13 | | - try { |
14 | | - const response = await fetch( |
15 | | - `/api/auth/naver/getToken?code=${url.searchParams.get("code")}`, |
16 | | - { |
17 | | - method: "GET", |
18 | | - headers: { |
19 | | - "Content-Type": "application/json", |
20 | | - }, |
21 | | - cache: "no-store", |
22 | | - credentials: "include", |
23 | | - }, |
24 | | - ); |
25 | | - |
26 | | - |
27 | | - if (!response.ok) { |
28 | | - throw new Error("Failed to login"); |
| 12 | + useEffect(() => { |
| 13 | + const url = new URL(window.location.href); |
| 14 | + |
| 15 | + const naverLogin = async () => { |
| 16 | + try { |
| 17 | + const response = await fetch( |
| 18 | + `/api/auth/naver/getToken?code=${url.searchParams.get("code")}`, |
| 19 | + { |
| 20 | + method: "GET", |
| 21 | + headers: { |
| 22 | + "Content-Type": "application/json", |
| 23 | + }, |
| 24 | + cache: "no-store", |
| 25 | + credentials: "include", |
| 26 | + } |
| 27 | + ); |
| 28 | + |
| 29 | + if (!response.ok) { |
| 30 | + throw new Error("Failed to login"); |
| 31 | + } |
| 32 | + |
| 33 | + // 액세스 토큰을 이용해서 사용자 정보 조회 |
| 34 | + const userDataResponse = await fetch("/api/auth/user"); |
| 35 | + if (userDataResponse.status === 200) { |
| 36 | + const userData = await userDataResponse.json(); |
| 37 | + authStore.setUser(userData); |
| 38 | + router.push("/"); |
| 39 | + } else { |
| 40 | + throw new Error("Failed to fetch user data"); |
| 41 | + } |
| 42 | + } catch (error) { |
| 43 | + console.error("로그인 실패", error); |
| 44 | + router.push("/auth/signin"); |
29 | 45 | } |
| 46 | + }; |
30 | 47 |
|
31 | | - // 액세스 토큰을 이용해서 사용자 정보 조회 |
32 | | - const userDataResponse = await fetch("/api/auth/user"); |
33 | | - if (userDataResponse.status == 200) { |
34 | | - const userData = await userDataResponse.json(); |
35 | | - authStore.setUser(userData); |
36 | | - router.push("/"); |
37 | | - } else { |
38 | | - throw new Error("Failed to fetch user data"); |
39 | | - } |
40 | | - } catch (error) { |
41 | | - console.error("로그인 실패", error); |
42 | | - router.push("/auth/signin"); |
43 | | - } |
44 | | - }; |
45 | | - |
46 | | - naverLogin(); |
| 48 | + naverLogin(); |
| 49 | + }, []); |
47 | 50 |
|
48 | 51 | return <AuthLoading />; |
49 | 52 | }; |
|
0 commit comments