Files
FitOS/admin/src/pages/users/UserForm.tsx

92 lines
3.0 KiB
TypeScript

import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api } from '../../api/client';
import { BackButton, Button, Card, ErrorText, Field, H1, Input, Select } from '../../components/ui';
import { useTopbar } from '../../topbar';
export default function UserForm() {
useTopbar({ title: 'Użytkownicy', back: '/users' });
const navigate = useNavigate();
const [form, setForm] = useState({
email: '',
password: '',
firstName: '',
lastName: '',
age: '',
isAdmin: false,
});
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setBusy(true);
try {
const data = await api<{ user: { id: string } }>('/admin/users', {
method: 'POST',
body: {
email: form.email,
password: form.password,
firstName: form.firstName || undefined,
lastName: form.lastName || undefined,
age: form.age ? parseInt(form.age) : undefined,
isAdmin: form.isAdmin,
},
});
navigate(`/users/${data.user.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
return (
<>
<BackButton to="/users" className="mb-4" />
<H1>Nowy użytkownik</H1>
<Card>
<form onSubmit={submit}>
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="E-mail">
<Input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required />
</Field>
<Field label="Hasło (min. 8)">
<Input
type="password"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
minLength={8}
required
/>
</Field>
<Field label="Imię">
<Input value={form.firstName} onChange={(e) => setForm({ ...form, firstName: e.target.value })} />
</Field>
<Field label="Nazwisko">
<Input value={form.lastName} onChange={(e) => setForm({ ...form, lastName: e.target.value })} />
</Field>
<Field label="Wiek">
<Input type="number" value={form.age} onChange={(e) => setForm({ ...form, age: e.target.value })} />
</Field>
<Field label="Administrator">
<Select
value={form.isAdmin ? '1' : '0'}
onChange={(e) => setForm({ ...form, isAdmin: e.target.value === '1' })}
>
<option value="0">Nie</option>
<option value="1">Tak</option>
</Select>
</Field>
</div>
{error && <ErrorText>{error}</ErrorText>}
<Button type="submit" disabled={busy}>
{busy ? 'Tworzenie…' : 'Utwórz użytkownika'}
</Button>
</form>
</Card>
</>
);
}