Programmatically submitting server action forms
Unanswered
Atlantic mackerel posted this in #help-forum
Atlantic mackerelOP
I've searched a bit and don't think anyone has asked this specific question, so here goes. This isn't really a problem I'm having – just something I'm curious about.
The App Router docs describe using
Is there any reason this method shouldn't be used? The docs don't specifically mention the pattern of submitting the form programmatically via a ref, so I wanted to make sure. I'm guessing there's no example like this in the docs just because it's fundamentally still the
If there aren't any good reasons against it, I can see it being useful; it still requires using a
The App Router docs describe using
startTransition() as a way to invoke a server action programmatically, but I've found that this also works:'use client'
import { useRef } from 'react'
import { myAction } from './actions'
export default function ClientComponent() {
const formRef = useRef(null)
const handleClick = () => {
if (confirm('Are you sure?') {
formRef.current?.requestSubmit()
}
}
return (
<>
<form
className="hidden"
ref={formRef}
action={myAction}
/>
<button onClick={handleClick}>
Do the Thing
</button>
</>
)
}Is there any reason this method shouldn't be used? The docs don't specifically mention the pattern of submitting the form programmatically via a ref, so I wanted to make sure. I'm guessing there's no example like this in the docs just because it's fundamentally still the
action prop invocation method.If there aren't any good reasons against it, I can see it being useful; it still requires using a
<form>, but it does seemingly provide a way to submit programmatically (e.g. conditionally based on confirmation) without resorting to startTransition() and losing out on PE benefits like the docs say. Anyone have thoughts?