How to not reset the form on submit with `use:enhance` in Svelte?
Asked Answered
T

2

12

I have a form that updates a product's information using a form with use:enhance and actions defined in +page.server.ts - However, whenever I submit the form, use:enhance resets the form elements and they all become blank, which is unexpected as the value for these elements is specified by $page.data.product, and the docs state that use:enhance runs invalidateAll.

Nonetheless, is there a way to stop this reset from occurring within the use:enhance function?

enter image description here

Theophylline answered 28/12, 2022 at 9:36 Comment(0)
H
16

As of #7326, you can pass a reset: false option to the update function in your enhance callback:

<script>
  import { enhance } from '$app/forms';
</script>

<form
  method="POST"
  use:enhance={() => {
    return async ({ update }) => {
      update({ reset: false });
    };
  }}>
  <input type="text" name="name" />
  <button>Submit</button>
</form>
Hiatt answered 2/2, 2023 at 14:46 Comment(2)
Where are the API docs covering the reset argument?Revalue
Great question - as far as I could tell there weren't any yet, which is what made finding this feature particularly tricky :)Hiatt
F
8

If you return a function from the use:enhance action, that function will be called when you get a response from the form submit. This function in turn gets an update function which takes an option reset that you can give the value false to not reset the form:

<script>
  import { enhance } from '$app/forms'
</script>

<form
  method="POST"
  use:enhance={() => {
    return async ({ update }) => {
      await update({ reset: false });
    };
  }}
>
  <input type="text" name="name" />
  <button>Submit</button>
</form>
Frontier answered 28/12, 2022 at 11:18 Comment(2)
Where are the API docs covering the reset argument?Revalue
@AndreyMikhaylov-lolmaus kit.svelte.dev/docs/types#public-types-submitfunction - You can see it in the type definition of the SubmitFunction argument provided to use:enhance hereTheophylline

© 2022 - 2024 — McMap. All rights reserved.