Use saved code
This commit is contained in:
+7
-22
@@ -1,6 +1,8 @@
|
||||
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;
|
||||
@@ -26,29 +28,12 @@ export default function Form<T = unknown>(props: FormProps<T>) {
|
||||
|
||||
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);
|
||||
const result = await post_json<T>(props.action, body, props.method);
|
||||
submitting.value = false;
|
||||
|
||||
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;
|
||||
}
|
||||
if (result.ok) props.on_success(result.data);
|
||||
else if (props.on_error) props.on_error(result.error);
|
||||
else error.value = result.error;
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user