Action return data lets you send information back after a form or event happens. It helps update the page or show messages without reloading.
0
0
Action return data in Svelte
Introduction
You want to show a success message after submitting a form.
You need to update part of the page based on user input.
You want to handle errors and show them to the user.
You want to keep the page interactive without full reloads.
Syntax
Svelte
export const actions = { default: async ({ request }) => { const formData = await request.formData(); // process data return { success: true, message: 'Saved!' }; } };
The actions object holds functions that run on form submission.
Each action returns an object with data to send back to the page.
Examples
Returns an error if name is missing, otherwise returns success and the name.
Svelte
export const actions = { default: async ({ request }) => { const formData = await request.formData(); const name = formData.get('name'); if (!name) { return { error: 'Name is required' }; } return { success: true, name }; } };
Multiple actions can be defined for different buttons or events.
Svelte
export const actions = { save: async ({ request }) => { const data = await request.formData(); // save data logic return { saved: true }; }, delete: async ({ request }) => { // delete logic return { deleted: true }; } };
Sample Program
This SvelteKit example uses +page.svelte and +page.server.js. When submitted, it checks if the name is given. If not, it shows an error. If yes, it greets the user by name.
Svelte
<!-- +page.svelte --> <script> export let data; </script> <form method="post"> <input name="name" placeholder="Your name" /> <button type="submit">Send</button> </form> {#if data?.error} <p style="color: red;">{data.error}</p> {:else if data?.success} <p style="color: green;">Hello, {data.name}!</p> {/if} <!-- +page.server.js --> export const actions = { default: async ({ request }) => { const formData = await request.formData(); const name = formData.get('name'); if (!name) { return { error: 'Name is required' }; } return { success: true, name }; } };
OutputSuccess
Important Notes
Returned data from actions is available in the page as data.
Use optional chaining like data?.error to avoid errors if no data yet.
Actions run on the server but return data to update the client smoothly.
Summary
Action return data sends info back after form events.
Use it to show success, errors, or update UI without reload.
Returned data is accessed in the page as data.