Skip to main content

Lesson 7 of 8

Mini Project: Task Manager - Part 9 (React Frontend)

Build the Task Manager frontend - a typed Context provider, task list with filter state, create task form, typed table with sorting, and a useTaskForm custom hook. All data flows through typed props and hooks with zero `any`.

18 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Task Manager Part 9 - Complete Typed React App

Task Manager Part 9 - Complete Typed React App
// src/hooks/useTaskForm.ts - typed form hook ─────────────────
interface TaskFormState {
  title:       string;
  priority:    Priority;
  description: string;
  dueDate:     string;   // string for input, converted to Date on submit
}

interface TaskFormActions {
  setField: <K extends keyof TaskFormState>(key: K, value: TaskFormState[K]) => void;
  reset:    () => void;
  submit:   () => Promise<void>;
}

const INITIAL_FORM: TaskFormState = {
  title: "", priority: "medium", description: "", dueDate: "",
};

export function useTaskForm(
  onSuccess: (task: Task) => void,
): [TaskFormState, TaskFormActions, string | null] {
  const [form,  setForm]  = React.useState<TaskFormState>(INITIAL_FORM);
  const [error, setError] = React.useState<string | null>(null);

  function setField<K extends keyof TaskFormState>(k: K, v: TaskFormState[K]): void {
    setForm((prev) => ({ ...prev, [k]: v }));
  }

  function reset(): void { setForm(INITIAL_FORM); setError(null); }

  async function submit(): Promise<void> {
    if (!form.title.trim()) { setError("Title is required"); return; }
    try {
      const task = await taskApi.create({
        title:    form.title.trim(),
        priority: form.priority,
      });
      onSuccess(task);
      reset();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to create task");
    }
  }

  return [form, { setField, reset, submit }, error];
}

// src/components/CreateTaskForm.tsx
export function CreateTaskForm(): React.ReactElement {
  const { createTask } = useTaskContext();
  const [form, actions, error] = useTaskForm(createTask);

  const handleSubmit = (e: React.FormEvent): void => {
    e.preventDefault();
    void actions.submit();
  };

  return (
    <form onSubmit={handleSubmit} className="create-task-form">
      <input
        value={form.title}
        onChange={(e) => actions.setField("title", e.target.value)}
        placeholder="Task title..."
        required
      />
      <select
        value={form.priority}
        onChange={(e) => actions.setField("priority", e.target.value as Priority)}
      >
        {(["low","medium","high","critical"] as Priority[]).map((p) => (
          <option key={p} value={p}>{p}</option>
        ))}
      </select>
      {error && <p className="error">{error}</p>}
      <button type="submit">Create Task</button>
    </form>
  );
}

// src/components/TaskTable.tsx - typed sortable table ─────────
type SortKey    = "title" | "priority" | "status";
type SortConfig = { key: SortKey; direction: "asc" | "desc" };

export function TaskTable(): React.ReactElement {
  const { tasks, deleteTask, updateTask } = useTaskContext();
  const [sort, setSort] = React.useState<SortConfig | null>(null);
  const [filter, setFilter] = React.useState<TaskStatus | "all">("all");

  const processed: Task[] = React.useMemo(() => {
    let result = filter === "all" ? tasks : tasks.filter((t) => t.status === filter);
    if (sort) {
      result = [...result].sort((a, b) => {
        const va = a[sort.key] ?? "";
        const vb = b[sort.key] ?? "";
        const dir = sort.direction === "asc" ? 1 : -1;
        return va < vb ? -dir : va > vb ? dir : 0;
      });
    }
    return result;
  }, [tasks, filter, sort]);

  function toggleSort(key: SortKey): void {
    setSort((prev) =>
      prev?.key === key
        ? { key, direction: prev.direction === "asc" ? "desc" : "asc" }
        : { key, direction: "asc" }
    );
  }

  return (
    <div>
      <select value={filter} onChange={(e) => setFilter(e.target.value as TaskStatus | "all")}>
        <option value="all">All</option>
        {(["todo","in-progress","done","archived"] as TaskStatus[]).map((s) => (
          <option key={s} value={s}>{s}</option>
        ))}
      </select>
      <table>
        <thead>
          <tr>
            {(["title","priority","status"] as SortKey[]).map((key) => (
              <th key={key} onClick={() => toggleSort(key)} style={{ cursor: "pointer" }}>
                {key} {sort?.key === key ? (sort.direction === "asc" ? "↑" : "↓") : ""}
              </th>
            ))}
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {processed.map((task) => (
            <tr key={task.id}>
              <td>{task.title}</td>
              <td>{task.priority}</td>
              <td>{task.status}</td>
              <td>
                <button onClick={() => void updateTask(task.id, { status: "done" })}>✅</button>
                <button onClick={() => void deleteTask(task.id)}>🗑️</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Common Mistakes

  • Not wrapping async event handlers with `void` - `onClick={() => deleteTask(id)}` where `deleteTask` is async returns a Promise that React ignores. Write `onClick={() => void deleteTask(id)}` to signal the ignored return intentionally.
  • Mutating sorted arrays - `tasks.sort()` mutates the original. Always spread first: `[...tasks].sort(...)`. With the `noUncheckedIndexedAccess` tsconfig option, this is doubly important.
  • Forgetting to memoize context callbacks with `useCallback` - every time the provider re-renders, inline functions are new references. Consumers subscribed to those functions re-render unnecessarily. Always `useCallback` for context-provided functions.

Tip

Tip

Practice Mini Project Task Manager Part 9 React Frontend in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Task Manager - Part 9 (React Frontend)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Task Manager Part 9 React Frontend from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Task Manager Part 9 React Frontend is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • Build the Task Manager frontend - a typed Context provider, task list with filter state, create task form, typed table with sorting, and a useTaskForm custom hook.
  • Not wrapping async event handlers with `void` - `onClick={() => deleteTask(id)}` where `deleteTask` is async returns a Promise that React ignores. Write `onClick={() => void deleteTask(id)}` to signal the ignored return intentionally.
  • Mutating sorted arrays - `tasks.sort()` mutates the original. Always spread first: `[...tasks].sort(...)`. With the `noUncheckedIndexedAccess` tsconfig option, this is doubly important.
  • Forgetting to memoize context callbacks with `useCallback` - every time the provider re-renders, inline functions are new references. Consumers subscribed to those functions re-render unnecessarily. Always `useCallback` for context-provided functions.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done