The completion flag is always false.
Likely cause: The server expects a different checkbox value or the control name differs.
Check and correct: Keep name="completed" and compare the submitted value with "on" as the example does.
PROJECT 4 · LESSON 12 OF 18
Edit titles, toggle completion and delete persistent records.
Continue from lesson 11: Create tasks with a Server Action. 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.
Creating a task chooses new values; editing must identify an existing record and change only its editable fields. Deletion must identify the intended record without accidentally creating or modifying another one.
A hidden ID is a convenient input, not proof of access. This local shared-data lab validates ID shape; Project 5 adds ownership checks to every mutation.
Map database records to plain component props. The editor needs a string ID, title and boolean, not an entire database document.
MongoDB documents have ObjectId identifiers, while hidden form inputs carry strings. The page converts _id to a string before supplying TaskEditor. The action checks that the incoming string is a 24-character hexadecimal ID and constructs an ObjectId for the database filter.
The hidden input identifies the requested record but does not protect it. Anyone can change a hidden value. This project still uses shared local data; lesson 15 adds the verified user ID to the filter so an ID alone is no longer enough to update a task.
updateOne receives a filter and an update document. The filter selects the record with the requested _id. $set changes title and completed without replacing the entire document, so createdAt remains intact. No upsert is enabled: a missing task must not silently become a new one.
matchedCount tells us whether a record matched. It is different from modifiedCount: saving exactly the same values can match a task while changing zero fields. Report success for a valid unchanged record instead of falsely claiming it is missing.
A checked checkbox without an explicit value submits "on". An unchecked checkbox normally submits no entry. The comparison data.get("completed") === "on" therefore maps both states into a boolean. The title is trimmed and validated again; the create form’s validation does not protect an independent edit request.
TaskEditor has one form for saving and another for deletion. Nesting them would be invalid HTML and make submission behavior unreliable. Each operation has its own action result and pending flag. The buttons are disabled while either operation is pending to avoid conflicting ordinary interactions.
deleteOne removes the matching document and reports deletedCount. A zero count may mean another request already removed it. Returning a clear message lets the learner distinguish “nothing matched” from a database exception.
The editor uses uncontrolled inputs initialized with defaultValue and defaultChecked. Its key includes the saved fields so updated server data remounts the form with those defaults. This is a simple teaching choice; a larger editor may use controlled state to handle unsaved edits and concurrent changes more carefully.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The page turns a stored task into plain editor props.
The user submits an ID, title and checkbox state.
The action validates input and updates or deletes the matching document.
The route refreshes and displays the database result, including the empty state after the last deletion.
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 { ObjectId } from "mongodb";
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." };
}
export async function updateTask(
_previous: Result,
data: FormData,
): Promise<Result> {
const id = String(data.get("id") ?? "");
const title = String(data.get("title") ?? "").trim();
if (!/^[a-f0-9]{24}$/i.test(id) || !title || title.length > 120)
return { message: "Check the task ID and title." };
try {
const result = await tasks.updateOne(
{ _id: new ObjectId(id) },
{ $set: { title, completed: data.get("completed") === "on" } },
);
if (!result.matchedCount) return { message: "Task no longer exists." };
} catch {
return { message: "Could not update task." };
}
revalidatePath("/");
return { message: "Task updated." };
}
export async function deleteTask(
_previous: Result,
data: FormData,
): Promise<Result> {
const id = String(data.get("id") ?? "");
if (!/^[a-f0-9]{24}$/i.test(id)) return { message: "Invalid task ID." };
try {
const result = await tasks.deleteOne({ _id: new ObjectId(id) });
if (!result.deletedCount) return { message: "Task no longer exists." };
} catch {
return { message: "Could not delete task." };
}
revalidatePath("/");
return { message: "Task deleted." };
}
This supplies independent save and delete forms for one existing task.
"use client";
import { useActionState } from "react";
import { updateTask, deleteTask } from "@/app/actions";
export default function TaskEditor({
task,
}: {
task: { id: string; title: string; completed: boolean };
}) {
const [edit, save, saving] = useActionState(updateTask, { message: "" });
const [deletion, remove, deleting] = useActionState(deleteTask, {
message: "",
});
return (
<article>
<form action={save}>
<input type="hidden" name="id" value={task.id} />
<label>
Title{" "}
<input
name="title"
defaultValue={task.title}
required
maxLength={120}
/>
</label>
<label>
<input
type="checkbox"
name="completed"
defaultChecked={task.completed}
/>{" "}
Completed
</label>
<button disabled={saving || deleting}>Save changes</button>
<p role="status">{edit.message}</p>
</form>
<form action={remove}>
<input type="hidden" name="id" value={task.id} />
<button disabled={saving || deleting}>Delete task</button>
<p role="status">{deletion.message}</p>
</form>
</article>
);
}
This Server Component reads the task list and composes the appropriate task controls.
import { tasks } from "@/lib/tasks";
import NewTask from "@/components/new-task";
import TaskEditor from "@/components/task-editor";
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) => (
<TaskEditor
key={task._id.toString() + task.title + task.completed}
task={{
id: task._id.toString(),
title: task.title,
completed: task.completed,
}}
/>
))}
{!rows.length && <p>No tasks yet.</p>}
</>
);
}
In one tab, delete a task. In a second tab that still displays it, submit its old edit form.
The update reports that the task no longer exists; it does not recreate it.
The database filter has no match and updateOne is not configured with upsert. Stale UI must not imply that a record still exists.
Do not put a form inside another form. Each edit and delete operation has its own form.
Likely cause: The server expects a different checkbox value or the control name differs.
Check and correct: Keep name="completed" and compare the submitted value with "on" as the example does.
Likely cause: The code checked modifiedCount instead of matchedCount.
Check and correct: Use matchedCount to decide whether the target existed.
Add a deletion confirmation and a filter for completed tasks.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
The stored _id has an ObjectId type. A raw string is not the same BSON value, even if its characters look identical.
No. Two valid edits can overwrite each other under last-write-wins behavior. Version checks are a separate extension.