import type { ComponentChildren } from "preact"; import { useSignal } from "@preact/signals"; import { post_json } from "@/src/client.ts"; 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 = ""; const result = await post_json(props.action, body, props.method); submitting.value = false; if (result.ok) props.on_success(result.data); else if (props.on_error) props.on_error(result.error); else error.value = result.error; } return (
{props.children}
{error.value && }
); }