deno.land / x / netzo@0.5.16 / components / blocks / form-fetch.tsx

form-fetch.tsx
نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// adapted from https://stackoverflow.com/a/74202858import type { ComponentChildren, JSX } from "preact";
export type FormFetchProps = JSX.IntrinsicElements["form"] & { id: string; method: "get" | "post" | "put" | "patch" | "delete"; action: string; children?: ComponentChildren;};
/** * An isomorphic form component that overrides the default submit (GET/POST) * with an HTTP Request using fetch to allow for GET/POST/PUT/PATCH/DELETE * * @example POST /rest/users * <FormFetch id="users.post" action="/rest/users" method="post"> * * @example PATCH /rest/users/:id * <FormFetch id="users.patch" action={`/rest/users/${user.id}`} method="patch"> * * @example DELETE /rest/users/:id * <FormFetch id="users.delete" action={`/rest/users/${user.id}`} method="delete"> * * @param {string} props.id - The id of the form * @param {string} props.action - The URL to send the form data to * @param {string} props.method - The HTTP method to use (GET/POST/PUT/PATCH/DELETE) * @returns {JSX.Element} - The form component */export const FormFetch = ({ id, action, method = "post", ...props}: FormFetchProps) => { return ( <> <form id={id} method={method} action={action} {...props}> {props.children} </form> <script dangerouslySetInnerHTML={{ __html: ` const form = document.getElementById("${id}"); form.addEventListener("submit", async (e) => { e.preventDefault(); const formData = new FormData(form); try { const response = await fetch("${action}", { method: "${method.toUpperCase()}", body: JSON.stringify(Object.fromEntries(formData)) }); const data = await response.json(); globalThis.location.reload(); } catch (error) { console.error(error); } }); `, }} /> </> );};
netzo

Version Info

Tagged at
a year ago