'use client'; import { useState } from 'react'; type User = { id: number; username: string; email: string; firstName: string | null; lastName: string | null; role: string; createdAt: string; }; type Props = { users: User[]; currentUserId: string; }; export default function UserAdminClient({ users: initial, currentUserId }: Props) { const [users, setUsers] = useState(initial); const [loading, setLoading] = useState(null); const [error, setError] = useState(null); async function toggleRole(user: User) { const newRole = user.role === 'admin' ? 'user' : 'admin'; setLoading(user.id); setError(null); try { const res = await fetch(`/api/admin-users/${user.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ role: newRole }), }); if (!res.ok) { const body = await res.json().catch(() => ({})); throw new Error(body.message ?? 'Okänt fel'); } const updated: User = await res.json(); setUsers((prev) => prev.map((u) => (u.id === updated.id ? { ...u, role: updated.role } : u))); } catch (e: any) { setError(e.message); } finally { setLoading(null); } } return ( <> {error && (
{error}
)} {users.map((user) => { const isSelf = String(user.id) === currentUserId; return ( ); })}
Användarnamn E-post Namn Roll Skapad Åtgärd
{user.username} {user.email} {[user.firstName, user.lastName].filter(Boolean).join(' ') || '—'} {user.role} {new Date(user.createdAt).toLocaleDateString('sv-SE')} {isSelf ? ( Du själv ) : ( )}
); }