formssveltesveltekitprogressive-enhancement

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


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


Solution

  • 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>