use `undefined` instead of `null` for empty `form` prop
See original GitHub issueDescribe 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
Issue Analytics
- State:
- Created a year ago
- Comments:8 (8 by maintainers)
You may use the relatively new JS/TS language feature “?”:
form?.errors?.blabla
Every “?.*” junction will return
undefined
if the l.h.s. is undefined or null, and the original value otherwise.I think this conversation is moving in a different direction.
My initial suggestion was to just use
undefined
instead ofnull
to be able to set an initial default value when the page loads. Withundefined
we could use the same concept as for regular Svelte components. Once a form gets submitted the developer is responsible for returning a useful value or to handle cases where nothing gets returned.