import type { ComponentChildren } from "preact"; import { useSignal } from "@preact/signals"; interface FormProps { action: string; on_success: (data: T) => void; on_error?: (message: string) => void; class?: string; method?: string; children: ComponentChildren; } // Posts the form's named fields as a JSON object of strings export default function Form(props: FormProps) { const submitting = useSignal(false); const error = useSignal(""); async function submit(event: SubmitEvent) { event.preventDefault(); if (submitting.value) { return; } const form = event.currentTarget as HTMLFormElement; const body = Object.fromEntries(new FormData(form)); submitting.value = true; error.value = ""; try { const method = props.method ?? "POST"; const response = await fetch( props.action, method.toUpperCase() === "GET" ? { method } : { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }, ); const data = response.status === 204 ? undefined : await response.json().catch(() => undefined); if (!response.ok) { throw new Error(data?.error ?? `Request failed with status ${response.status}`); } props.on_success(data as T); } catch (err) { const message = err instanceof Error ? err.message : String(err); if (props.on_error) props.on_error(message); else error.value = message; } finally { submitting.value = false; } } return (
{props.children}
{error.value &&

{error.value}

}
); }