I am building a simple form component following the Svelte documentation, which says that I can access the form action data from an external component using the page state.
When I destructure form
from the page state, it is undefined.
However, I can access it if I do page.form
directly.
Why is that? What am I missing?
<script lang="ts">
import { enhance } from "$app/forms";
import { page } from "$app/state";
let pageDate = page; // pageDate.form is defined
// let { form } = page; -> form is undefined
</script>
<h3>Login</h3>
{#if pageDate.form?.error}
<p class="error">{pageDate.form?.error}</p>
{/if}
<form method="POST" action="?/login" use:enhance>
<label>
Email
<input name="email" type="email">
</label>
<label>
Password
<input name="password" type="password">
</label>
<button>Log in</button>
</form>
By destructuring, you get the property just once; it will be undefined
on initial page load and stay that way.
You can make the destructuring reactive via $derived
:
let { form } = $derived(page);