Digital Dreamer

Calling a SvelteKit form action (or submitting a form) from a component

Submitting a form from a SvelteKit component can be tricky. Here's how to handle form submissions and bind form responses correctly within your components.

Calling a SvelteKit form action (or submitting a form) from a component

Handling Form Submissions from a SvelteKit Component

Submitting a form from a SvelteKit component can be tricky. Here's how to handle form submissions and bind form responses correctly within your components.

1. Create the FormTestComponent and Add a Form

svelte
<script>
  import { enhance } from '$app/forms';
  export let form;
</script>

<form method="POST" action="?/testAction" use:enhance>
  <input type="text" name="name" placeholder="Enter your name" />
  <button type="submit">Submit</button>
</form>

{#if form?.success}
  <p>Success! Hello {form.name}</p>
{/if}

2. Set Up +page.svelte for Form Binding

svelte
<script>
  import FormTestComponent from './FormTestComponent.svelte';
  export let form;
</script>

<FormTestComponent {form} />

3. Enhancing the Form Submission

To handle the response within the component, you can use the enhance action with a callback:

svelte
<form 
  method="POST" 
  action="?/testAction" 
  use:enhance={() => {
    return async ({ result, update }) => {
      if (result.type === 'success') {
        console.log('Form submitted successfully!', result.data);
      }
      update();
    };
  }}
>
  ...
</form>

4. Creating the Server-side Action

javascript
export const actions = {
  testAction: async ({ request }) => {
    const data = await request.formData();
    const name = data.get('name');

    return {
      success: true,
      name
    };
  }
};

Conclusion: By passing the form prop down to your components and using use:enhance, you can maintain a clean separation of concerns while still having powerful form handling capabilities.

Happy Hacking!