|
| 1 | +import { invalidate } from '$app/navigation'; |
| 2 | + |
1 | 3 | // this action (https://svelte.dev/tutorial/actions) allows us to |
2 | 4 | // progressively enhance a <form> that already works without JS |
3 | | -export function enhance(form, { pending, error, result }) { |
| 5 | +export function enhance(form, { pending, error, result } = {}) { |
4 | 6 | let current_token; |
5 | 7 |
|
6 | 8 | async function handle_submit(e) { |
7 | 9 | const token = (current_token = {}); |
8 | 10 |
|
9 | 11 | e.preventDefault(); |
10 | 12 |
|
11 | | - const body = new FormData(form); |
| 13 | + const data = new FormData(form); |
12 | 14 |
|
13 | | - if (pending) pending(body, form); |
| 15 | + if (pending) pending({ data, form }); |
14 | 16 |
|
15 | 17 | try { |
16 | | - const res = await fetch(form.action, { |
| 18 | + const response = await fetch(form.action, { |
17 | 19 | method: form.method, |
18 | 20 | headers: { |
19 | 21 | accept: 'application/json' |
20 | 22 | }, |
21 | | - body |
| 23 | + body: data |
22 | 24 | }); |
23 | 25 |
|
24 | 26 | if (token !== current_token) return; |
25 | 27 |
|
26 | | - if (res.ok) { |
27 | | - result(res, form); |
| 28 | + if (response.ok) { |
| 29 | + if (result) result({ data, form, response }); |
| 30 | + |
| 31 | + const url = new URL(form.action); |
| 32 | + url.search = url.hash = ''; |
| 33 | + invalidate(url.href); |
28 | 34 | } else if (error) { |
29 | | - error(res, null, form); |
| 35 | + error({ data, form, error: null, response }); |
30 | 36 | } else { |
31 | | - console.error(await res.text()); |
| 37 | + console.error(await response.text()); |
32 | 38 | } |
33 | 39 | } catch (e) { |
34 | 40 | if (error) { |
35 | | - error(null, e, form); |
| 41 | + error({ data, form, error: e, response: null }); |
36 | 42 | } else { |
37 | 43 | throw e; |
38 | 44 | } |
|
0 commit comments