The action receives the wrong argument.
Likely cause: It was written as a one-argument FormData action while being used through useActionState.
Check and correct: Use the previous-result, FormData signature shown in this lesson.
PROJECT 4 · LESSON 11 OF 18
Connect a form to a validated database write and refresh the list.
Continue from lesson 10: Read tasks from a database. Keep existing files; create or replace the complete files listed below.
Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.
Reading a database is only half of a task app. We now connect an HTML form to a server-side operation, and follow its input, validation, database write and refreshed output. This is the core pattern reused by later edit and admin forms.
A form action invokes a server function over a network request. use server marks the action module, while useActionState connects its result and pending status to the form.
HTML required helps the user, but server validation decides what is acceptable. After insertion, revalidatePath refreshes the visible route. Reading tasks remains the Server Component’s job.
NewTask is a Client Component because it displays pending and result state through useActionState. Its form action is the action function returned by that hook. When submitted, the named controls are collected into FormData and the framework invokes createTask on the server.
The imported function looks like an ordinary function reference, but crossing from client to server requires a network request. Next.js handles that transport for a Server Action. use server marks the action module’s server functions; it does not mean the function is private or callable only through your visible form.
With useActionState, the action receives the previous result first and FormData second. _previous is unused in this example. The returned object becomes state, and pending tracks an in-flight submission. That explains the function signature rather than treating its arguments as boilerplate.
data.get("title") reads the control whose name is title. An input’s label or id alone does not make it a submitted field. The code converts the value to a string, trims whitespace and rejects an empty or overlong title before contacting MongoDB.
The browser’s required and maxLength attributes help normal users, but a direct request can bypass them. The server repeats the real rule. For example, three spaces satisfy a simple nonempty HTML input but become an empty string after trim. That request should not insert a task.
insertOne stores the normalized title, completed false, and a server-created date. The caller does not decide the initial completion flag or timestamp in this feature. We accept a small input contract rather than blindly copying every incoming field into a document.
After insertion, revalidatePath("/") tells Next.js that the task route needs fresh output. The updated server render queries the list again. This keeps MongoDB as the source of truth instead of manually appending a guessed record to a client list.
Expected validation failures return a message without throwing. A database failure returns a safe retry message, while detailed diagnostics belong in server logs. The pending button prevents ordinary repeated clicks, but it does not provide database-level deduplication; the order lesson introduces that separate concern.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The user submits a named title control.
The Server Action normalizes and validates FormData.
A valid title is inserted into MongoDB; invalid input returns feedback without a write.
revalidatePath refreshes the task route, and the action result updates the form message.
The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
This module owns the task mutations and their server-side validation.
"use server";
import { revalidatePath } from "next/cache";
import { tasks } from "@/lib/tasks";
export type Result = { message: string };
export async function createTask(
_previous: Result,
data: FormData,
): Promise<Result> {
const title = String(data.get("title") ?? "").trim();
if (!title || title.length > 120)
return { message: "Enter a title between 1 and 120 characters." };
try {
await tasks.insertOne({ title, completed: false, createdAt: new Date() });
} catch {
return { message: "Could not save. Please try again." };
}
revalidatePath("/");
return { message: "Task added." };
}
This connects the create action’s feedback and pending state to a form.
"use client";
import { useActionState } from "react";
import { createTask } from "@/app/actions";
export default function NewTask() {
const [state, action, pending] = useActionState(createTask, { message: "" });
return (
<form action={action}>
<label>
New task <input name="title" required maxLength={120} />
</label>
<button disabled={pending}>{pending ? "Saving…" : "Add task"}</button>
<p role="status">{state.message}</p>
</form>
);
}
This Server Component reads the task list and composes the appropriate task controls.
import { tasks } from "@/lib/tasks";
import NewTask from "@/components/new-task";
export const dynamic = "force-dynamic";
export default async function TasksPage() {
const rows = await tasks
.find({})
.sort({ createdAt: -1 })
.limit(100)
.toArray();
return (
<>
<h1>Tasks</h1>
<NewTask />
{rows.map((task) => (
<article key={task._id.toString()}>
{task.title} — {task.completed ? "Done" : "Open"}
</article>
))}
{!rows.length && <p>No tasks yet.</p>}
</>
);
}
Remove the input’s name temporarily and submit a title. Restore it afterward.
The action receives no title value and returns its validation message.
FormData is built from successful named form controls. Visible text in an unnamed input is not enough to populate data.get("title").
Return expected validation failures as data. Do not show raw database exceptions to learners or users.
Likely cause: It was written as a one-argument FormData action while being used through useActionState.
Check and correct: Use the previous-result, FormData signature shown in this lesson.
Likely cause: The mutation succeeded without refreshing the affected route.
Check and correct: Call revalidatePath for the list route after the successful write and before returning success.
Add a minimum title length of three and update the feedback.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
Rendering reads the data in a Server Component. Server Actions here represent user-triggered mutations, not a replacement for every server-side function.
No. It controls execution placement. Authentication and authorization must be explicitly checked when the application introduces private data.