Submitting forms with a non-JS backend

My web application is a SPA that talks to a Go backend. I have the following questions: - Should I be using action(...) and useSubmission(...) or should I be using a callback bound the form's onsubmit property? - It seems actions have the option to either run on client or server side. In my scenario, I would be using the logic in action to a) validate the input elements and b) make an asychronous call to the Go server with the form data. Is it always necessary for my to provide the action name (as the second arg) to action(...). Seems strange to have to provide it even if I don't plan to use actions on the server side. - If I understand correctly, action(...) won't work unless I have marked my form with method="post". Is it bad if I make a PUT request inside of the action despite having marked my form with method="post"?
4 Replies
Madaxen86
Madaxen863mo ago
The purpose of actions are to invalidate queries. So if you don't you queries you may also not need actions. Since you have a SPA and rely on JS on the client anyways you're better of using onSubmit for as you mentioned validation etc. If you're using queries I'd recommend useAction so you can use it in onSubmit
const userAction = action(async (data:FormData) =>{
//...
// validate...
return reload({revalidate:queryUser.key})
}/,"userAction")
const queryUser = query(async () => /*...*/,"queryUser")
function MyForm() {
const action = useAction(userAction)
const submission = useSubmission(userAction)
return <form onSubmit={async (e) => {
e.preventDefault()
const data = new Formdata(e.target);
await action(data)
}}>

<input disabled={submission.pending} name="name" />
}
const userAction = action(async (data:FormData) =>{
//...
// validate...
return reload({revalidate:queryUser.key})
}/,"userAction")
const queryUser = query(async () => /*...*/,"queryUser")
function MyForm() {
const action = useAction(userAction)
const submission = useSubmission(userAction)
return <form onSubmit={async (e) => {
e.preventDefault()
const data = new Formdata(e.target);
await action(data)
}}>

<input disabled={submission.pending} name="name" />
}
useSubmission is just an observer for actions. You can use any method inside actions you like.
FatFreeButter
FatFreeButterOP3mo ago
Thanks. Is it possible to doredirect(...) wthin an onsubmit function.
Madaxen86
Madaxen863mo ago
Passing the the action to the form directly makes sense for progressive enhancement, which is not an option if you need cloent side validation. Sure inside you action you could do:
const userAction = action(async (data:FormData) =>{
//...
// validate...
return redirect({revalidate:queryUser.key})
}/,"userAction")
const userAction = action(async (data:FormData) =>{
//...
// validate...
return redirect({revalidate:queryUser.key})
}/,"userAction")
reload just means "stay on the same route"
FatFreeButter
FatFreeButterOP3mo ago
Thanks, this was super helpful

Did you find this page helpful?