Isomorphic form handling?
See original GitHub issueIs your feature request related to a problem? Please describe.
When you need to use a form like <form action="/items" method="POST">
, currently you have two choices:
- leave it as it is, and when it’s submitted, the page refreshes, and then redirects to a new page.
- hijack the submission, and use
fetch()
to submit to a different api that doesn’t redirect, and usegoto()
to redirect the page
The API for these two destinations might be wildly different, one accepts form data, and the other probably json, and if you don’t do #2
to save the trouble, the SPA flow is going to be interrupted whenever you need to use a form. If you don’t do #1
, then javascript is required to use the site.
It’d be nice if svelte kit can handle the two case as transparently as it does for <a>
Describe the solution you’d like
I don’t have a solution in mind yet, since redirection seems to be transparent to fetch()
. I’m currently just asking if this is a problem worth solving.
People are actually trying to implement this themselves as can be seen from this issue
Describe alternatives you’ve considered
How important is this feature to you? Somewhat, a page refresh is not the end of the world.
Additional context
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
Yep. If you look at the demo app’s todos page, we’re using an
enhance
action that progressively enhances a form if JS is available: https://github.com/sveltejs/kit/blob/aa3610bc3608814f775d89dcff6ed5995343ce5b/packages/create-svelte/templates/default/src/routes/todos/index.svelte#L55-L62The
enhance
action uses anaccepts
header to signal that it’s coming fromfetch
(there may be a more semantically appropriate way to do this, but e.g.sec-fetch-dest
isn’t supported widely enough yet, so this’ll do for now): https://github.com/sveltejs/kit/blob/master/packages/create-svelte/templates/default/src/lib/form.ts#L27-L33Our endpoints have to have some special logic that returns a redirect if it sees that header: https://github.com/sveltejs/kit/blob/master/packages/create-svelte/templates/default/src/routes/todos/_api.ts#L30-L42
This works — try https://svelte-kit-demo.richard-a-harris.workers.dev/todos with and without JS — but it’s definitely not as turnkey as it should be. We need to figure out where
enhance
should live (whether it’s part of Kit, or a standalone package or whatever) and how to make the redirect logic more seamless, since it’s not very portable.Yeah, that was the only real option I could think of. But on a large form that’s potentially a lot of state to (manually…) serialize and deserialize through a bug ugly url.
It’s particularly unfortunate because even in something as mindless as PHP this (i.e., rendering a page after a POST) would be completely trivial