Demo available on the SvelteLab REPL
Created
August 8, 2024 07:31
-
-
Save hyunbinseo/cbfe9142a7ab9d153ba786c0ac9bcfce to your computer and use it in GitHub Desktop.
Block form double submit in SvelteKit use:enhance
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
export const actions = { | |
default: () => ({ updatedAt: new Date() }) | |
}; |
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> | |
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