Files
2026-10-29 21:42:26 -03:00

47 lines
1.3 KiB
TypeScript

import type { ComponentChildren } from "preact";
import { useSignal } from "@preact/signals";
import { post_json } from "@/src/client.ts";
interface FormProps<T> {
action: string;
on_success: (data: T) => void;
on_error?: (message: string) => void;
class?: string;
method?: string;
headers?: Record<string, 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 = "";
const result = await post_json<T>(props.action, body, props.method, props.headers);
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 (
<form class={props.class} onSubmit={submit}>
<fieldset disabled={submitting.value}>{props.children}</fieldset>
{error.value && <p role="alert" class="mt-4 text-error-600 dark:text-error-400">{error.value}</p>}
</form>
);
}