Svelte and SvelteKit course ยท Module 13: Form Actions
use:enhance - Progressive Enhancement
In this lesson3
Basic usage
<script>
import { enhance } from '$app/forms';
</script>
<form method="POST" use:enhance>
<input name="name" />
<button>Add</button>
</form>By default:
- Prevents page reload
- Updates the
formprop - Refreshes the page data (reruns
load)
Custom enhance
<script>
import { enhance } from '$app/forms';
let loading = $state(false);
</script>
<form
method="POST"
use:enhance={() => {
loading = true;
return async ({ result, update }) => {
loading = false;
if (result.type === 'success') {
// Custom logic
showToast('Added!');
}
// Call the default update
await update();
};
}}
>
<input name="name" disabled={loading} />
<button disabled={loading}>
{loading ? 'Adding...' : 'Add'}
</button>
</form>The loading variable is declared with $state because we change it in the callback and want the button to lock right away.
Optimistic UI
<script>
import { enhance } from '$app/forms';
let { data } = $props();
let optimisticWarriors = $state([]);
let allWarriors = $derived([...data.warriors, ...optimisticWarriors]);
</script>
<form
method="POST"
use:enhance={({ formData }) => {
const name = formData.get('name');
// Add optimistically
const tempId = Date.now();
optimisticWarriors = [...optimisticWarriors, { id: tempId, name }];
return async ({ result, update }) => {
// Remove the temporary one
optimisticWarriors = optimisticWarriors.filter(w => w.id !== tempId);
await update();
};
}}
>
<!-- ... -->
</form>
{#each allWarriors as warrior}
<p>{warrior.name}</p>
{/each}The allWarriors list is a $derived: it recalculates by itself when data.warriors or optimisticWarriors changes. In Svelte 4 we would have written it with $:.
Code for this lesson: App.svelte
<script>
// use:enhance - Progressive Enhancement
let warriors = $state([
{ id: 1, name: 'Ragnar' },
{ id: 2, name: 'Bjorn' }
]);
let loading = $state(false);
let newName = $state('');
// Simulating use:enhance
async function handleSubmit(e) {
e.preventDefault();
if (!newName.trim()) return;
loading = true;
// Simulating server delay
await new Promise(r => setTimeout(r, 1000));
warriors = [...warriors, { id: Date.now(), name: newName }];
newName = '';
loading = false;
}
async function handleDelete(id) {
loading = true;
await new Promise(r => setTimeout(r, 500));
warriors = warriors.filter(w => w.id !== id);
loading = false;
}
</script>
<main class="enhance-demo">
<h1>use:enhance</h1>
<p class="subtitle">Progressive Enhancement</p>
<section class="code">
<h2>How use:enhance works</h2>
<pre>
{"<"}script{">"}
import {"{"} enhance {"}"} from '$app/forms';
{"<"}/script{">"}
{"<"}form method="POST" use:enhance{">"}
{"<"}input name="name" /{">"}
{"<"}button{">"}Add{"<"}/button{">"}
{"<"}/form{">"}
</pre>
<p class="hint">
Works without JS (fallback)
With JS: no page reload
</p>
</section>
<section>
<h2>Add warrior</h2>
<form onsubmit={handleSubmit} class="add-form">
<input
bind:value={newName}
placeholder="Warrior name"
disabled={loading}
/>
<button type="submit" disabled={loading}>
{loading ? '...' : '+'} Add
</button>
</form>
</section>
<section>
<h2>List ({warriors.length})</h2>
{#each warriors as warrior (warrior.id)}
<div class="warrior">
<span>{warrior.name}</span>
<form onsubmit={(e) => { e.preventDefault(); handleDelete(warrior.id); }}>
<button type="submit" class="delete" disabled={loading}>
Delete
</button>
</form>
</div>
{/each}
</section>
<section class="custom">
<h2>Custom enhance callback</h2>
<pre>
{"<"}form use:enhance={"{"}({"{"} formData {"}"}) => {"{"}
// Before sending
loading = true;
return async ({"{"} result, update {"}"}) => {"{"}
// After response
loading = false;
if (result.type === 'success') {"{"}
// Custom logic
{"}"}
await update(); // Default update
{"}"};
{"}"}{"}"}{">"}
</pre>
</section>
</main>
<style>
.enhance-demo {
font-family: 'Georgia', serif;
max-width: 500px;
margin: 0 auto;
padding: 2rem;
background: #1a0f0a;
color: #e8d5b7;
min-height: 100vh;
}
h1 {
color: #d4af37;
text-align: center;
}
.subtitle {
text-align: center;
color: #8b7355;
}
section {
background: rgba(212, 175, 55, 0.1);
border: 1px solid #d4af37;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
}
h2 {
color: #d4af37;
font-size: 1rem;
margin-top: 0;
}
pre {
background: rgba(0,0,0,0.5);
padding: 1rem;
border-radius: 4px;
font-size: 0.8rem;
overflow-x: auto;
}
.hint {
font-size: 0.85rem;
color: #90ee90;
margin-top: 0.5rem;
}
.add-form {
display: flex;
gap: 0.5rem;
}
input {
flex: 1;
padding: 0.75rem;
background: rgba(0,0,0,0.3);
border: 1px solid #3d2914;
border-radius: 4px;
color: #e8d5b7;
}
input:disabled {
opacity: 0.5;
}
button {
padding: 0.75rem 1rem;
background: #3d2914;
color: #e8d5b7;
border: 1px solid #d4af37;
border-radius: 4px;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.warrior {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem;
background: rgba(0,0,0,0.3);
border-radius: 4px;
margin-bottom: 0.5rem;
}
.delete {
background: #8b0000;
border-color: #8b0000;
padding: 0.5rem;
}
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does use:enhance do on a form?