Skip to lesson content

PROJECT 4 · LESSON 12 OF 18

Complete task CRUD

Edit titles, toggle completion and delete persistent records.

  • ObjectId
  • updateOne
  • deleteOne
  • error results

Your workspace: task-app

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.

1. Understand the problem and the concepts

Why we need this feature

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.

Understand the ID across the browser boundary

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.

Read updateOne and its result

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.

Keep edit and delete submissions separate

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.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The page turns a stored task into plain editor props.

  2. The user submits an ID, title and checkbox state.

  3. The action validates input and updates or deletes the matching document.

  4. The route refreshes and displays the database result, including the empty state after the last deletion.

Read an edit as a database operation

  1. Start with a task titled Read notes and completed=false.
  2. Change the input to Read routing notes, check Completed, and submit.
  3. The action receives the string ID, normalized title and "on". $set stores the new title and true.
  4. createdAt is unchanged. Saving the same values again still has matchedCount=1 even if no stored field changes.

3. Build it, one file at a time

  1. Replace app/actions.ts with the complete version below, then add TaskEditor and replace the page.
  2. Edit a title, tick Completed, and save. Delete a different task.
  3. Refresh after every operation. The database, not a browser array, is the source of truth.

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.

app/actions.ts

This module owns the task mutations and their server-side validation.

app/actions.ts
"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." };
}

Read the code

  1. use server marks its exported async operations as Server Functions. Through useActionState they receive the previous result and submitted FormData.
  2. createTask trims the title, checks length, inserts normalized data and then revalidates the list route. Expected failures return message objects instead of exposing raw exceptions.
  3. updateTask validates the string ID before constructing ObjectId, then uses $set for editable fields. matchedCount distinguishes a missing target from an unchanged valid task.
  4. deleteTask validates the target ID and checks deletedCount. Successful mutations revalidate the same list route.
  5. This checkpoint is an unauthenticated shared-data lab for local practice. Do not present it as private until lesson 15 adds session and ownership checks.

components/task-editor.tsx

This supplies independent save and delete forms for one existing task.

components/task-editor.tsx
"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>
  );
}

Read the code

  1. The task prop contains plain strings and booleans, not the MongoDB document object. Its hidden ID specifies the requested target.
  2. defaultValue and defaultChecked initialize uncontrolled inputs. The page’s key strategy remounts the editor when saved fields change.
  3. Each form uses its own useActionState result. The two forms are siblings, not nested, and both pending flags disable conflicting ordinary operations.

app/page.tsx

This Server Component reads the task list and composes the appropriate task controls.

app/page.tsx
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>}
    </>
  );
}

Read the code

  1. The async page awaits a database cursor converted to an array. sort requests newest first and limit bounds the teaching example.
  2. force-dynamic keeps the task read request-rendered. An empty array renders the empty message rather than an exception.
  3. MongoDB ObjectIds are converted to strings before becoming component keys or client editor props.
  4. NewTask owns form feedback. The page still owns the database read; the mutation revalidates this route to obtain updated rows.
  5. TaskEditor receives only id, title and completed. Its key changes with saved fields so uncontrolled inputs receive refreshed defaults.

4. Run it and check your result

  • Create, read, edit, complete and delete all persist.
  • Submitting an invalid ID returns a message rather than crashing.

5. Predict, change and observe

In one tab, delete a task. In a second tab that still displays it, submit its old edit form.

Compare your prediction with the expected result

What you should observe

The update reports that the task no longer exists; it does not recreate it.

Why it happens

The database filter has no match and updateOne is not configured with upsert. Stale UI must not imply that a record still exists.

6. Troubleshoot with evidence

A common mistake

Do not put a form inside another form. Each edit and delete operation has its own form.

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.

Saving unchanged text says Task not found.

Likely cause: The code checked modifiedCount instead of matchedCount.

Check and correct: Use matchedCount to decide whether the target existed.

7. Practice and explain it back

Your independent task

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.

Why convert the ID back to ObjectId?

The stored _id has an ObjectId type. A raw string is not the same BSON value, even if its characters look identical.

Does input validation solve concurrent editing?

No. Two valid edits can overwrite each other under last-write-wins behavior. Version checks are a separate extension.