Refactor ProfileDropdown to fetch user details, simplify logout flow, and enhance dropdown UI; add /api/me route for user data retrieval.
This commit is contained in:
@@ -1,35 +1,29 @@
|
||||
'use client'
|
||||
|
||||
import {useState, useRef, useEffect} from 'react'
|
||||
import {useRouter} from 'next/navigation'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
export default function ProfileDropdown() {
|
||||
const [open, setOpen] = useState(false)
|
||||
const dropdownRef = useRef<HTMLDivElement>(null)
|
||||
const [profile, setProfile] = useState<{ user?: string; email?: string }>({})
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setOpen(false)
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
fetch('/api/me')
|
||||
.then((res) => res.json())
|
||||
.then((data) => setProfile(data))
|
||||
.catch(() => setProfile({}))
|
||||
}, [])
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await fetch('/logout', {method: 'POST'})
|
||||
router.push('/') // Or a dedicated post-logout landing page
|
||||
} catch (e) {
|
||||
console.error('Logout failed', e)
|
||||
}
|
||||
await fetch('/logout', { method: 'POST' })
|
||||
router.push('/')
|
||||
}
|
||||
|
||||
const name = profile.email || profile.user || 'Loading...'
|
||||
|
||||
return (
|
||||
<div className="relative" ref={dropdownRef}>
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setOpen(!open)}
|
||||
className="text-white font-medium px-4 py-2 hover:bg-zinc-800 rounded"
|
||||
@@ -38,10 +32,13 @@ export default function ProfileDropdown() {
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="absolute right-0 mt-2 w-40 bg-white shadow-lg rounded z-50">
|
||||
<div className="absolute right-0 mt-2 w-56 bg-white shadow-lg rounded z-50 text-zinc-900 overflow-hidden text-sm">
|
||||
<div className="px-4 py-2 border-b border-zinc-200 font-medium">
|
||||
{name}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="block w-full text-left px-4 py-2 text-sm text-zinc-800 hover:bg-zinc-100"
|
||||
className="block w-full text-left px-4 py-2 hover:bg-zinc-100"
|
||||
>
|
||||
Logout
|
||||
</button>
|
||||
|
||||
Reference in New Issue
Block a user