61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
import type { ComponentChildren } from "preact";
|
|
import { useSignal } from "@preact/signals";
|
|
|
|
interface FormProps<T> {
|
|
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<T = unknown>(props: FormProps<T>) {
|
|
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 (
|
|
<form class={props.class} onSubmit={submit}>
|
|
<fieldset disabled={submitting.value}>{props.children}</fieldset>
|
|
{error.value && <p role="alert">{error.value}</p>}
|
|
</form>
|
|
);
|
|
}
|