typescriptsveltesveltekit

How to fetch default action in +page.server.ts file in SvelteKit


I'm using SvelteKit and I've a form on my page. As I need to manipulate the data before it is sent, I cannot use the SvelteKit's default behaviour of form submission (using action attribute).

So, according to this part of the documentation, I used a simple event listener and then the fetch function :

async function handleSubmit(e:Event) {
  const formData = new FormData(e.target as HTMLFormElement);
  // ... doing some stuff here
  const res = await fetch("?/login", { /* plenty of stuff there */ });
}

So the action named "login" in ./+page.server.ts will be executed.

I have a simple question: what path do I write (in fetch) if I want the default action to be executed, knowing that the current page is in a slug.

Do I write fetch("?/") ? (doesn't work)

Do I write fetch("?") ? (doesn't work)

Obviously I could just name it and problem solved. I'm just wondering if there is a solution and if someone has ever thought about this.


Solution

  • Don't do this.

    Set up the form as usual and use the enhance action, which can be provided with a callback to intercept and modify the submission.

    From the docs:

    <form
      method="POST"
      use:enhance={({ form, data, action, cancel }) => {
        // `form` is the `<form>` element
        // `data` is its `FormData` object
        // `action` is the URL to which the form is posted
        // `cancel()` will prevent the submission
    
        return async ({ result, update }) => {
          // `result` is an `ActionResult` object
          // `update` is a function which triggers the logic that would be triggered if this callback wasn't set
        };
      }}
    >
    

    If you just want to add data, you do not even have to return anything from the function, e.g.

    <script lang="ts">
        import { enhance, type SubmitFunction } from '$app/forms';
    
        const onSubmit: SubmitFunction = ({ data }) => {
            data.set('test', 'value');
        }
    </script>
    
    <form method="POST" use:enhance={onSubmit}>
      ...
    </form>
    

    Of course there also is the old fashioned way: Just add type=hidden inputs to the form instead. If the data does not have to change, this would be the most robust approach, as it does not require any JS to make the form send the data.


    As for what the default action is: It's just the current URL, document.location.href.