0
0
Svelteframework~5 mins

Why form actions handle mutations in Svelte

Choose your learning style9 modes available
Introduction

Form actions handle mutations to safely change data on the server when a user submits a form. This keeps your app organized and secure.

When a user submits a form to create or update information, like signing up or editing a profile.
When you want to process form data on the server without reloading the whole page.
When you need to validate and save user input securely before showing a result.
When you want to keep your app responsive by handling data changes smoothly.
When you want to separate data-changing logic from display logic for clarity.
Syntax
Svelte
export const actions = {
  default: async ({ request }) => {
    const formData = await request.formData();
    // process formData and perform mutation
    return { success: true };
  }
};

The actions object defines functions that run when a form is submitted.

Each function receives the form data and can update the server or database.

Examples
Basic form action that reads a 'name' field and saves it.
Svelte
export const actions = {
  default: async ({ request }) => {
    const data = await request.formData();
    const name = data.get('name');
    // save name to database
    return { success: true };
  }
};
Named action to update a user profile field.
Svelte
export const actions = {
  updateProfile: async ({ request }) => {
    const data = await request.formData();
    const email = data.get('email');
    // update user email in database
    return { updated: true };
  }
};
Sample Program

This SvelteKit example uses a form in +page.svelte and a default action in +page.server.js to handle the form submission. When the user submits the username, the action reads it and returns a success message, which is displayed on the page after re-render.

Svelte
<!-- +page.svelte -->
<script>
  export let data;
</script>

<form method="POST">
  <label for="username">Username:</label>
  <input id="username" name="username" required />
  <button type="submit">Save</button>
  {#if data?.message}
    <p>{data.message}</p>
  {/if}
</form>

<!-- +page.server.js -->

export const actions = {
  default: async ({ request }) => {
    const formData = await request.formData();
    const username = formData.get('username');
    // pretend to save username
    return { success: true, message: `Saved username: ${username}` };
  }
};
OutputSuccess
Important Notes

Form actions run on the server, so they can safely change data without exposing logic to the browser.

Using form actions helps keep your app secure and organized by separating data changes from UI code.

Summary

Form actions handle data changes when users submit forms.

They run on the server to keep data safe and app organized.

Use them to process, validate, and save form data smoothly.