Skip to content

Instantly share code, notes, and snippets.

@khromov
Created June 13, 2023 00:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khromov/c8ba9583f844081583e00fafae103bef to your computer and use it in GitHub Desktop.
Save khromov/c8ba9583f844081583e00fafae103bef to your computer and use it in GitHub Desktop.
use:form action
<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>
// 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);
}
@iwhcto
Copy link

iwhcto commented Jun 20, 2023

How using on:form-response knows it has to search for src/lib/form.js?
I feel I'm missing a step of understanding.
Tku

@mattnaus
Copy link

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