import {useEffect, useState} from 'react'; import {apiFetch} from '../utils/api.js'; import {sessionStamp} from '../utils/auth.js'; import {normalizeProfileStyle} from '../utils/profileStyle.js'; /** * The stored role, the active role ("view as"), the display name and the public profile style of the logged-in * user, or null while loading and on any error. * Loads again after a new login or a role switch (see sessionStamp) on the next render. */ export default function useCurrentUser(enabled) { const [user, setUser] = useState(null); const stamp = sessionStamp(); useEffect(() => { if (!enabled || !stamp) { setUser(null); return undefined; } let cancelled = false; (async () => { try { const response = await apiFetch(`${import.meta.env.VITE_API_URL}/api/users/me?v=1`); const data = response.ok ? await response.json() : null; if (!cancelled) setUser(data && {role: data.role, activeRole: data.activeRole ?? data.role, displayName: data.displayName, profileStyle: normalizeProfileStyle(data.settings?.profileStyle)}); } catch { if (!cancelled) setUser(null); } })(); return () => { cancelled = true; }; }, [enabled, stamp]); return user; }