-
-
Save khromov/c8ba9583f844081583e00fafae103bef to your computer and use it in GitHub Desktop.
use:form action
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
// src/routes/+layout.svelte | |
import Toasts, { toasts } from "./Toasts.svelte"; | |
function show_toast({ detail: { json } }) { | |
if (json.error) { | |
toasts.error(json.error.message); | |
} else { | |
toasts.success(json.message); | |
} | |
} | |
</script> | |
<Toasts /> | |
<div on:form-response={show_toast}> | |
<slot /> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/lib/form.js | |
export default function form(form_element) { | |
form_element.setAttribute('novalidate', true); | |
async function handle_submit(event) { | |
event.preventDefault(); | |
function validate() { | |
// https://css-tricks.com/form-validation-part-2-constraint-validation-api-javascript/ | |
} | |
const is_valid = validate(); | |
if (!is_valid) return; | |
const response = await fetch(event.target.getAttribute('action'), { | |
method: event.target.getAttribute('method'), | |
body: new FormData(event.target) | |
}); | |
const json = await response.json(); | |
event.target.dispatchEvent( | |
new CustomEvent('form-response', { bubbles: true, detail: { json } }) | |
); | |
} | |
form_element.addEventListener('submit', handle_submit); | |
} |
import { form } from '$lib/form'
appears to be missing from +layout.svelte
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How using
on:form-response
knows it has to search forsrc/lib/form.js
?I feel I'm missing a step of understanding.
Tku