Reading Form Data
Part of the Next.js Essentials section of Coddy's React journey — lesson 31 of 47.
Your action receives one argument: a FormData object. It's a browser built-in, and you only need one method from it:
export async function addNote(formData) {
const text = formData.get('text');
const author = formData.get('author');
saveNote(text, author);
}The string you pass to get() is not the input's id, and not its label. It is the name attribute:
<input name="author" /> → formData.get('author')An input with no name is invisible to the form. It renders, you can type in it, and its value simply never arrives: formData.get() hands back null. This is the single most common bug in a first server-action form, and it fails quietly.
get() always returns a string (or null), so a number field needs converting:
const quantity = Number(formData.get('quantity'));Challenge
EasyThe notes form is wired up, but nothing useful gets saved: the inputs have no name, and the action saves two empty strings.
- In
app/page.jsx, addname="text"to the first input andname="author"to the second. - In
app/actions.js, read both fields offformDatainstead of using the empty strings.
Keep the ids as they are, and keep the saveNote(text, author) call: only the two values above it change.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
2Routing & Links
Folders Are RoutesNested RoutesLinking PagesDynamic RoutesNot Found PagesRecap: Routing3Layouts & Metadata
The Root LayoutShared NavigationNested LayoutsPage MetadataDynamic MetadataRecap: Layouts6Server Actions
What Is a Server ActionForms That ActReading Form DataRefreshing the PageRecap: Server Actions