Skip to content

use undefined instead of null for empty form prop #7178

@ivanhofer

Description

@ivanhofer

Describe the problem

Using the new actions feature of SvelteKit, when loading the page the form prop is set to null. In my usecase I return an errors object if some of the form fields don't pass the validation in the action.

To not having to deal with unnecessary if checks or optional chainings, I'm setting errors to an empty object when the page loads and form is still null.

<script>
	export let form
	$: ({ errors } = form || { errors: { } }
</script>

{#if errors.email}
	invalid email address
{/if}

{#if form.errors.password} <!-- Uncaught TypeError: Cannot read properties of null (reading 'errors') -->
	please enter a stronger password
{/if}

This works fine, if I only use the errors object in that file. But if I accidentially access form again, I'll get an error because form is still null.

To not having the issue above I would need to set the default value like this:

<script>
	export let form
	$: form = form || { errors: { } }
</script>

But this requires me to write additional code.

Describe the proposed solution

form should be undefined and not null to make it possible to set a fallback value like you would do in other Svelte components:

<script>
	export let form = { errors: { } }
	$: ({ errors } = form
</script>

{#if errors.email}
	invalid email address
{/if}

{#if form.errors.password} <!-- no error! -->
	please enter a stronger password
{/if}

Alternatives considered

Leave it as it is.

Importance

would make my life easier

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    breaking changefeature / enhancementNew feature or requestformsStuff relating to forms and form actionsneeds-decisionNot sure if we want to do this yet, also design work neededp3-edge-caseSvelteKit cannot be used in an uncommon way

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions