Is it possible to not reset an enhanced SvelteKit form after successful submit?
Asked Answered
R

2

5

I have the following enhanced SvelteKit form:

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

<form method="POST" use:enhance>
  <input name="name" />
</form>

When it is submitted successfully the form is reset. Is there any way to avoid this?

Rego answered 7/1, 2023 at 16:12 Comment(0)
R
10

You can customize the behavior of the enhance action further by providing it a submit function. This function in turn can return a callback that is called when the form has been submitted.

The update property in the first parameter of this callback is a function that will trigger the logic that would be triggered if this callback wasn't set, and it takes an option reset which allows you to not reset the form after successful submit.

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

  function handleSubmit() {
    // ...

    return async ({ update }) => {
      await update({ reset: false });
    };
  }
</script>

<form method="POST" use:enhance={handleSubmit}>
  <input name="name" />
</form>
Rego answered 7/1, 2023 at 16:12 Comment(0)
V
0

If you (like me) want to have an action that works like enhance but that never resets the entered values in the <form>, I think you can use the following customEnhance that I just wrote for this specific purpose:

custom-enhance.js

import { enhance } from '$app/forms';

export function customEnhance(form, submitFunction) {

    function customSubmitFunction() {
        return async (actionResult) => {
            await actionResult.update({reset: false})
            if(submitFunction){
                await submitFunction(actionResult)
            }
        }
    }

    return enhance(form, customSubmitFunction)

}

+page.svelte

<script>
import { customEnhance } from './custom-enhance'
</script>
<form method="POST" use:customEnhance>
   <!-- Does never reset form values, but does otherwise work like "enhance". -->
   ...
</form>

I haven't tested it much yet, so no guarantees I got the implementation right, but works good for me so far :)

Vehicle answered 20/4, 2023 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.