|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect, useState } from 'react'; |
| 4 | +import { useRouter } from 'next/navigation'; |
| 5 | +import { signOut, useSession } from 'next-auth/react'; |
| 6 | +import { Loader2 } from 'lucide-react'; |
| 7 | +import { useUser } from '@/components/UserContext'; |
| 8 | + |
1 | 9 | /** |
2 | | - * @file Dashboard/page.js |
3 | | - * @brief User Dashboard Component with User Data Fetching. |
4 | | - * @details This component displays a user's information after fetching data from the backend API. |
5 | | - * The user data includes name, email, and phone number. The component uses `useEffect` to fetch the |
6 | | - * user information on component mount and updates the state with the received data. Errors during |
7 | | - * data fetching are handled and logged to the console. |
8 | | - * @returns {JSX.Element} - A dashboard component displaying user details. |
9 | | - ***************************************************************** |
10 | | - * @component Details |
11 | | - * - Uses `useState` to store user data once it's fetched from the API. |
12 | | - * - Uses `useEffect` to perform the fetch operation upon component mount. |
13 | | - * - Displays user information such as name, email, and phone number, if available. |
14 | | - * - Error handling is implemented to catch and log any issues during data fetching. |
15 | | - ***************************************************************** |
| 10 | + * Dashboard component that displays user information and handles session management |
16 | 11 | */ |
| 12 | +export default function Dashboard() { |
| 13 | + const router = useRouter(); |
| 14 | + const { data: session, status } = useSession(); |
| 15 | + const { user, userLoggedOut } = useUser(); |
| 16 | + const [loading, setLoading] = useState(true); |
| 17 | + const [userData, setUserData] = useState(null); |
| 18 | + const [error, setError] = useState(''); |
17 | 19 |
|
| 20 | + useEffect(() => { |
| 21 | + // Check authentication status |
| 22 | + if (status === 'unauthenticated') { |
| 23 | + router.push('/users/Login'); |
| 24 | + return; |
| 25 | + } |
18 | 26 |
|
19 | | -'use client'; |
| 27 | + // Fetch additional user data if needed |
| 28 | + const fetchUserData = async () => { |
| 29 | + if (!session?.user) return; |
20 | 30 |
|
21 | | -import { useUser } from '@/components/UserContext'; |
22 | | -import { signOut } from 'next-auth/react'; |
| 31 | + try { |
| 32 | + const response = await fetch('https://your-api.com/user?name=${encodeURIComponent(session.user.name)}`', { |
| 33 | + method: 'GET', |
| 34 | + headers: { |
| 35 | + 'Content-Type': 'application/json', |
| 36 | + //Authorization: `Bearer ${session.user.token}`, // Use token from session |
| 37 | + }, |
| 38 | + }); |
23 | 39 |
|
24 | | -export default function Dashboard() { |
25 | | - const { user } = useUser(); |
| 40 | + if (!response.ok) { |
| 41 | + throw new Error('Failed to fetch user data'); |
| 42 | + } |
| 43 | + |
| 44 | + const data = await response.json(); |
| 45 | + setUserData(data); |
| 46 | + } catch (error) { |
| 47 | + console.error('Error fetching user data:', error); |
| 48 | + setError('Failed to load user information'); |
| 49 | + } finally { |
| 50 | + setLoading(false); |
| 51 | + } |
| 52 | + }; |
| 53 | + |
| 54 | + // Only fetch additional data for credentials login |
| 55 | + // For Google login, use session data directly |
| 56 | + if (session?.user?.provider === 'credentials') { |
| 57 | + fetchUserData(); |
| 58 | + } else { |
| 59 | + setUserData(session?.user); |
| 60 | + setLoading(false); |
| 61 | + } |
| 62 | + }, [session, status, router]); |
| 63 | + |
| 64 | + // Handle sign out |
| 65 | + const handleSignOut = async () => { |
| 66 | + try { |
| 67 | + await signOut({ |
| 68 | + redirect: false |
| 69 | + }); |
| 70 | + userLoggedOut(); // Clear UserContext |
| 71 | + router.push('/users/Login'); |
| 72 | + } catch (error) { |
| 73 | + console.error('Sign out error:', error); |
| 74 | + setError('Failed to sign out. Please try again.'); |
| 75 | + } |
| 76 | + }; |
| 77 | + |
| 78 | + // Loading state |
| 79 | + if (loading || status === 'loading') { |
| 80 | + return ( |
| 81 | + <div className="min-h-screen bg-base-200 flex items-center justify-center"> |
| 82 | + <Loader2 className="w-12 h-12 text-primary animate-spin" /> |
| 83 | + </div> |
| 84 | + ); |
| 85 | + } |
26 | 86 |
|
| 87 | + // Error state |
| 88 | + if (error) { |
| 89 | + return ( |
| 90 | + <div className="min-h-screen bg-base-200 flex items-center justify-center"> |
| 91 | + <div className="card w-full max-w-md shadow-xl bg-base-100"> |
| 92 | + <div className="card-body items-center text-center"> |
| 93 | + <div className="text-red-500 mb-4">{error}</div> |
| 94 | + <button |
| 95 | + className="btn btn-primary" |
| 96 | + onClick={() => router.push('/users/Login')} |
| 97 | + > |
| 98 | + Return to Login |
| 99 | + </button> |
| 100 | + </div> |
| 101 | + </div> |
| 102 | + </div> |
| 103 | + ); |
| 104 | + } |
| 105 | + |
| 106 | + // Render dashboard content |
27 | 107 | return ( |
28 | 108 | <div className="min-h-screen bg-base-200 flex items-center justify-center"> |
29 | 109 | <div className="card w-full max-w-md shadow-xl bg-base-100"> |
30 | 110 | <div className="card-body items-center text-center"> |
31 | | - {/* 用户头像 */} |
| 111 | + {/* User Avatar */} |
32 | 112 | <div className="avatar"> |
33 | 113 | <div className="w-24 rounded-full"> |
34 | | - <img src={user?.image || '/default-avatar.png'} alt="User Avatar" /> |
| 114 | + <img |
| 115 | + src={userData?.image || '/default-avatar.png'} |
| 116 | + alt="User Avatar" |
| 117 | + /> |
35 | 118 | </div> |
36 | 119 | </div> |
37 | | - {/* 欢迎信息 */} |
| 120 | + |
| 121 | + {/* Welcome Message */} |
38 | 122 | <h2 className="card-title text-2xl font-bold mt-4"> |
39 | | - Welcome, {user?.name || 'User'}! |
| 123 | + Welcome, {userData?.name || 'User'}! |
40 | 124 | </h2> |
41 | | - {/* 用户信息 */} |
42 | | - <p className="text-base"> |
43 | | - Your E-mail: {user?.email || 'N/A'} |
44 | | - </p> |
45 | | - <p className="text-base"> |
46 | | - Your Phone Number: {user?.phone || 'N/A'} |
47 | | - </p> |
48 | | - {/* 操作按钮 */} |
| 125 | + |
| 126 | + {/* User Information */} |
| 127 | + <div className="space-y-2 mt-4 w-full"> |
| 128 | + <p className="text-base"> |
| 129 | + <span className="font-semibold">Email:</span>{' '} |
| 130 | + {userData?.email || 'N/A'} |
| 131 | + </p> |
| 132 | + {userData?.phone && ( |
| 133 | + <p className="text-base"> |
| 134 | + <span className="font-semibold">Phone:</span>{' '} |
| 135 | + {userData.phone} |
| 136 | + </p> |
| 137 | + )} |
| 138 | + <p className="text-base"> |
| 139 | + <span className="font-semibold">Login Provider:</span>{' '} |
| 140 | + {session?.user?.provider === 'google' ? 'Google' : 'Email'} |
| 141 | + </p> |
| 142 | + </div> |
| 143 | + |
| 144 | + {/* Actions */} |
49 | 145 | <div className="card-actions mt-6"> |
50 | 146 | <button |
51 | 147 | className="btn btn-primary" |
52 | | - onClick={() => { |
53 | | - sessionStorage.removeItem('user'); |
54 | | - signOut({ callbackUrl: '/users/Login' }); |
55 | | - }} |
| 148 | + onClick={handleSignOut} |
56 | 149 | > |
57 | 150 | Sign Out |
58 | 151 | </button> |
|
0 commit comments