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

3.7k Views Asked by At

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

2

There are 2 best solutions below

2
tgordon18 On BEST ANSWER

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>
2
Tholle On

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>