How can I get the input field values from formData (using Next form action)
I’m probably missing something here, but I thought that
formData.get(inputId)
would work 🫠
Here’s is the code from a basic form I’ve just written to play around:
export default function BasicPage() {
async function handleSubmit(formData: FormData) {
'use server'
const firstName = formData.get('firstName')
const lastName = formData.get('lastName')
const email = formData.get('email')
console.log({ firstName, lastName, email })
}
return (
<main>
<span className="block h-16" />
<h1 className="text-6xl font-bold tracking-wide">Basic</h1>
<span className="block h-8" />
<form action={handleSubmit}>
<label htmlFor="firstName">First Name</label>
<span className="block h-2" />
<input
className="w-full rounded-sm px-3 py-2 text-gray-700"
id="firstName"
placeholder="John"
/>
<span className="block h-4" />
<label htmlFor="lastName">Last Name</label>
<span className="block h-2" />
<input
className="w-full rounded-sm px-3 py-2 text-gray-700"
id="lastName"
placeholder="Doe"
/>
<span className="block h-4" />
<label htmlFor="email">Email</label>
<span className="block h-2" />
<input
className="w-full rounded-sm px-3 py-2 text-gray-700"
id="email"
placeholder="[email protected]"
type="email"
/>
<span className="block h-8" />
<button
className="w-full rounded-sm bg-gray-700 py-3 text-gray-50 hover:bg-gray-600"
type="submit"
>
Submit
</button>
</form>
</main>
)
}
export default function BasicPage() {
async function handleSubmit(formData: FormData) {
'use server'
const firstName = formData.get('firstName')
const lastName = formData.get('lastName')
const email = formData.get('email')
console.log({ firstName, lastName, email })
}
return (
<main>
<span className="block h-16" />
<h1 className="text-6xl font-bold tracking-wide">Basic</h1>
<span className="block h-8" />
<form action={handleSubmit}>
<label htmlFor="firstName">First Name</label>
<span className="block h-2" />
<input
className="w-full rounded-sm px-3 py-2 text-gray-700"
id="firstName"
placeholder="John"
/>
<span className="block h-4" />
<label htmlFor="lastName">Last Name</label>
<span className="block h-2" />
<input
className="w-full rounded-sm px-3 py-2 text-gray-700"
id="lastName"
placeholder="Doe"
/>
<span className="block h-4" />
<label htmlFor="email">Email</label>
<span className="block h-2" />
<input
className="w-full rounded-sm px-3 py-2 text-gray-700"
id="email"
placeholder="[email protected]"
type="email"
/>
<span className="block h-8" />
<button
className="w-full rounded-sm bg-gray-700 py-3 text-gray-50 hover:bg-gray-600"
type="submit"
>
Submit
</button>
</form>
</main>
)
}
1 Reply
I realized my mistake 🫠
I had to set the name attribute on each input to be able to get their values from formData!