Skip to content

Instantly share code, notes, and snippets.

@hyunbinseo
Created August 8, 2024 07:31
Show Gist options
  • Save hyunbinseo/cbfe9142a7ab9d153ba786c0ac9bcfce to your computer and use it in GitHub Desktop.
Save hyunbinseo/cbfe9142a7ab9d153ba786c0ac9bcfce to your computer and use it in GitHub Desktop.
Block form double submit in SvelteKit use:enhance
export const actions = {
default: () => ({ updatedAt: new Date() })
};
<script>
import { enhance } from '$app/forms';
export let form;
let submitCount = 0;
/** @param {SubmitEvent} event */
const disableSubmitter = ({ submitter }) => {
if (submitter instanceof HTMLButtonElement) submitter.disabled = true;
};
/** @type {import('@sveltejs/kit').SubmitFunction} */
const delaySubmit = async () => {
// Delays progressively enhanced form submit:
const timer = new Promise((resolve) => setTimeout(resolve, 1000));
return async ({ update }) => {
await timer;
submitCount += 1;
await update();
};
};
</script>
<!-- Svelte's #if block can be used to show/hide forms. -->
<!-- This will allow svelte/transition if needed. -->
<form
style:display={submitCount ? 'none' : null}
on:submit={disableSubmitter}
use:enhance={delaySubmit}
method="post"
>
<button>Hasn't Submitted</button>
</form>
<form
style:display={!submitCount ? 'none' : null}
on:submit={disableSubmitter}
use:enhance={delaySubmit}
method="post"
>
<!-- use:enhance updates form to null and then the actual data. -->
<!-- As a result, this button is regenerated after submission. -->
<!-- Since it is regenerated, the disabled attribute is gone. -->
{#if form}
<button>Has Submitted ({submitCount})</button>
{/if}
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment