ciscoheat / sveltekit-superforms

Making SvelteKit forms a pleasure to use!
https://superforms.rocks
MIT License
2.26k stars 65 forks source link

Is it possible to use event.preventDefault() when executing onSubmit? #473

Closed es-ki closed 2 months ago

es-ki commented 2 months ago

When the onSubmit function is executed, the page reloads, preventing the API call within the onSubmit event. I want to prevent the page from reloading when onSubmit is executed.

In a standard form's onSubmit, executing event.preventDefault() can prevent the page from reloading. I would like to achieve the same behavior.

The current code is as follows:

<script lang="ts">
  const { form, errors, constraints, enhance } = superForm(dataForm, {
    resetForm: true,
    onSubmit: async ({ formData }) => {
      const entries = formData.entries();
      const data = Object.fromEntries(entries);
      const res = await fetch('/api/data', {
        method: 'POST',
    body: JSON.stringify(data)
      });
  ...
</script>

<form id="form" use:enhance>
...

Originally, I was using Form actions, but I wanted to enable prerender, so I switched to using API Routes instead.

ciscoheat commented 2 months ago

You can deconstruct cancel and use that, though in your case it looks like your should use SPA mode instead: https://superforms.rocks/concepts/spa

es-ki commented 2 months ago

@ciscoheat Resolved! Thanks!!