My HTML code is organized into two separate files, +page.svelte
and Role.svelte
. This division makes it easier to manage and maintain as I continue adding more svelte files to +page.svelte
in the future. The actual form is located within the Role.svelte
file.
After some research, I discovered that since the form
variable is only passed to +page.svelte
and not to any components, using $page.form
directly in Role.svelte
instead of declaring a separate variable like let form: ActionData
is recommended. However, I noticed that $page.form
does not provide type safety or inference like ActionData
. How can I ensure that $page.form
has the same type inference as let form: ActionData
while still maintaining my current file organization?
(The following is the code):
Role.svelte
<script lang="ts">
import { enhance } from "$app/forms";
import { page } from "$app/stores";
import type { ActionData } from "./$types";
let form: ActionData = $page.form // attempted but returned undefined
form = form // had no effect
let userRoles = ["admin", "student"];
</script>
<form method="post" action="?/role" use:enhance>
<!-- unable to work, had to resort to using $page.form which lacks typing -->
{#if form?.noSelectedRole}
<p>{form?.error}</p>
{/if}
<p>You are a/an...</p>
{#each userRoles as userRole}
<input type="radio" value={userRole} name="role" />
<label for={userRole}>{userRole}</label>
<br />
{/each}
<slot />
<!-- For when the school can't be found -->
<p>What school are you a part of? Type its DepEd school ID.</p>
<input type="text" name="schoolId" placeholder="School" />
<br />
<button type="submit">Check</button>
</form>
+page.svelte
<script lang="ts">
import { page } from "$app/stores";
import type { ActionData } from "./$types";
import Role from "./Role.svelte";
let form: ActionData = $page.form // did not produce desired results
</script>
<Role>
<p>
<!-- undefined result, had to rely on $page.form without proper typing :( -->
{console.log(form?.noSelectedRole)}
{#if form?.noSelectedRole}
Select a role please.
{/if}
</p>
</Role>
+page.server.ts
import type { Actions } from "./$types";
import { fail, redirect } from '@sveltejs/kit';
export const actions = {
role: async ({ request }) => {
const formData = await request.formData()
const userRole = formData.get("role") as string
const schoolId = formData.get("schoolId") as string
console.log(`role: ${userRole}`)
console.log(`school id: ${schoolId}`)
if (typeof userRole !== "string" ||
userRole == null) {
console.log("no user role selected")
return fail(400, {
noSelectedRole: true,
error: "Please select a role.",
data: {...{userRole, schoolId}}
})
}
}
} satisfies Actions;