import { h, type FunctionComponent, type TargetedSubmitEvent } from 'preact' import { useCallback } from 'preact/hooks' import rek, { type FetchError } from 'rek' import useRequestState from '../../shared/hooks/use_request_state.ts' import serializeForm from '../../shared/utils/serialize_form.ts' import Button from './button.tsx' import Checkbox from './checkbox.tsx' import Input from './input.tsx' import Message from './message.tsx' import sutil from './utility.module.scss' const AdmissionForm: FunctionComponent<{ admission?: ANY onCancel?: ANY onCreate?: ANY onUpdate?: ANY roles?: ANY[] }> = ({ admission, onCancel, onCreate, onUpdate, roles }) => { const [{ error, pending, success }, actions] = useRequestState() const create = useCallback(async (e: TargetedSubmitEvent) => { e.preventDefault() actions.pending() try { const form = e.currentTarget const result = await rek[admission ? 'patch' : 'post']( `/api/admissions${admission ? '/' + admission.id : ''}`, serializeForm(form), ) actions.success() if (admission) { onUpdate?.(result) } else { form.reset() onCreate?.(result) } } catch (err) { actions.error(err as FetchError) } }, []) return (
{success && ( Admission {admission ? 'updated' : 'created'}! )} {error && ( {error.status || 500} {error.body?.message || error.message} )} {roles && (
{roles.map((role) => ( r.id === role.id)} /> ))}
)}
{onCancel && ( )}
) } export default AdmissionForm