How do I access form data and errors from other pages? #8015
-
I'm following https://kit.svelte.dev/docs/form-actions, but I'm getting a bit stuck on accessing form data when using the form in a component outside of the initial route. There's an example in the docs, where you'd put your login action (from I see in https://kit.svelte.dev/docs/form-actions#anatomy-of-an-action there's a note about how For reference, my particular use-case is using an email sign-up input form in the footer:
So far I've made some progress showing loading and success with the following: <script>
import { enhance } from "$app/forms"
let loading = false
let successForm = false
</script>
...
{#if successForm}
<p>
(something about registering)
</p>
{:else}
<form
method="POST"
action="/email"
use:enhance={({ form, data, action, cancel }) => {
loading = true
return async ({ result, update }) => {
loading = false
if (result.data?.success) {
successForm = true
}
update()
}
}}
>
... This feels a bit off already, but then for errors, should I create a store where the action is originally defined? Or do it all within Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The issue was that calling
https://kit.svelte.dev/docs/form-actions#progressive-enhancement-use-enhance Otherwise, something like this example should work for you: <script>
// src/routes/+page.svelte
import { enhance, applyAction } from "$app/forms";
import { page } from '$app/stores';
let loading = false
</script>
{#if $page.form?.success}
<p>(something about registering)</p>
{:else}
<form
method="POST"
action="/email"
use:enhance={() => {
loading = true
return async ({ result, update }) => {
await applyAction(result) // manually call applyAction to update `page.form`
await update()
loading = false
}
}}
>
<button>Submit</button>
</form>
{/if} // src/routes/email/+page.server.js
import { invalid } from '@sveltejs/kit';
export const actions = {
default: () => {
// returning some data with invalid() also updates the `page.form` property
// return invalid(400, { missing: true, password })
return { success: true };
}
}; |
Beta Was this translation helpful? Give feedback.
The issue was that calling
update()
did not update thepage.form
values. See the reason below:https://kit.svelte.dev/docs/form-actions#progressive-enhancement-use-enhance
Otherwise, something like th…