Kurs Svelte i SvelteKit · Moduł 13: Akcje formularzy

use:enhance - Progressive Enhancement

2 min czytania ·
W tej lekcji3

Podstawowe użycie

<script>
  import { enhance } from '$app/forms';
</script>

<form method="POST" use:enhance>
  <input name="name" />
  <button>Dodaj</button>
</form>

Domyślnie:

  • Zapobiega przeładowaniu strony
  • Aktualizuje form prop
  • Odświeża dane strony (ponownie uruchamia load)

Customowy 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('Dodano!');
      }

      // Wywołaj domyślną aktualizację
      await update();
    };
  }}
>
  <input name="name" disabled={loading} />
  <button disabled={loading}>
    {loading ? 'Dodawanie...' : 'Dodaj'}
  </button>
</form>

Zmienna loading jest zadeklarowana przez $state, bo zmieniamy ją w callbacku i chcemy, żeby przycisk od razu się zablokował.

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');

    // Dodaj optymistycznie
    const tempId = Date.now();
    optimisticWarriors = [...optimisticWarriors, { id: tempId, name }];

    return async ({ result, update }) => {
      // Usuń tymczasowego
      optimisticWarriors = optimisticWarriors.filter(w => w.id !== tempId);

      await update();
    };
  }}
>
  <!-- ... -->
</form>

{#each allWarriors as warrior}
  <p>{warrior.name}</p>
{/each}

Lista allWarriors to $derived: przelicza się sama, gdy zmieni się data.warriors albo optimisticWarriors. W Svelte 4 zapisalibyśmy to jako $:.

Kod do tej lekcji: 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('');

  // Symulacja use:enhance
  async function handleSubmit(e) {
    e.preventDefault();
    if (!newName.trim()) return;

    loading = true;

    // Symulacja opóźnienia serwera
    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>Jak działa use:enhance</h2>
    <pre>
{"<"}script{">"}
  import {"{"} enhance {"}"} from '$app/forms';
{"<"}/script{">"}

{"<"}form method="POST" use:enhance{">"}
  {"<"}input name="name" /{">"}
  {"<"}button{">"}Dodaj{"<"}/button{">"}
{"<"}/form{">"}
    </pre>
    <p class="hint">
      Działa bez JS (fallback)
      Z JS: brak przeładowania strony
    </p>
  </section>

  <section>
    <h2>Dodaj wojownika</h2>
    <form onsubmit={handleSubmit} class="add-form">
      <input
        bind:value={newName}
        placeholder="Imię wojownika"
        disabled={loading}
      />
      <button type="submit" disabled={loading}>
        {loading ? '...' : '+'} Dodaj
      </button>
    </form>
  </section>

  <section>
    <h2>Lista ({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}>
            Usuń
          </button>
        </form>
      </div>
    {/each}
  </section>

  <section class="custom">
    <h2>Custom enhance callback</h2>
    <pre>
{"<"}form use:enhance={"{"}({"{"} formData {"}"}) => {"{"}
  // Przed wysłaniem
  loading = true;

  return async ({"{"} result, update {"}"}) => {"{"}
    // Po odpowiedzi
    loading = false;

    if (result.type === 'success') {"{"}
      // Custom logic
    {"}"}

    await update(); // Domyślna aktualizacja
  {"}"};
{"}"}{"}"}{">"}
    </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>

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Co robi use:enhance na formularzu?

  1. PytanieDziałanie use:enhance
  2. RozmowaPożegnanie z targiem w Birce

Przydatne artykuły