Capstone: Build a Typed React Task Tracker
Build a React task tracker with typed filters, accessible forms, versioned local storage, migration recovery, and a behavior test.
Build a small React and TypeScript task tracker with accessible forms, filters, and immutable updates. Its versioned storage migrates the earlier array format, keeps unsupported records for recovery, and tests that migration.
Capstone: Build a Typed React Task Tracker
Introduction
This capstone builds a personal task list with typed data, forms, filters, and browser persistence. It uses a React + TypeScript Vite scaffold. Create it and add the test dependencies:
npm create vite@latest task-tracker -- --template react-ts
cd task-tracker
npm install
npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event
The commands follow the Vite React TypeScript scaffold and the React Testing Library install guide. In vite.config.ts, keep the scaffold’s React plugin, import defineConfig from vitest/config, and add test: { environment: "jsdom" }. Vitest uses jsdom to provide browser APIs such as localStorage in component tests; see its test environment guide.
Add the storage module as src/task.ts, replace src/App.tsx, and put the tests in src/App.test.tsx. Keep local storage for a personal list in one browser. Use an authenticated server for shared, cross-device, or sensitive data.
Define task data and validate saved values
Put this module in src/task.ts. JSON.parse returns untrusted data, so the loader checks each record before it enters React state. Version 1 stored a bare array under its own key. The loader leaves that key in place, copies valid tasks into version 2, and carries rejected values or unparseable text forward so a later save cannot erase them.
export interface Task {
id: string;
title: string;
done: boolean;
}
export type TaskFilter = "all" | "active" | "done";
export const TASK_STORAGE_KEY = "typed-task-tracker:v2";
const LEGACY_TASK_STORAGE_KEY = "typed-task-tracker:v1";
const STORAGE_VERSION = 2 as const;
interface StoredTasks {
version: typeof STORAGE_VERSION;
tasks: Task[];
rejected: unknown[];
recoveryRaw: string | null;
}
interface TaskLoadResult {
tasks: Task[];
rejected: unknown[];
recoveryRaw: string | null;
warning: string;
shouldPersist: boolean;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isTask(value: unknown): value is Task {
if (typeof value !== "object" || value === null) return false;
const task = value as Record<string, unknown>;
return (
typeof task.id === "string" &&
task.id.length > 0 &&
typeof task.title === "string" &&
task.title.trim().length > 0 &&
typeof task.done === "boolean"
);
}
function splitTasks(values: unknown[]) {
const tasks: Task[] = [];
const rejected: unknown[] = [];
for (const value of values) {
if (isTask(value)) tasks.push(value);
else rejected.push(value);
}
return { tasks, rejected };
}
function recoveryWarning(rejected: unknown[], recoveryRaw: string | null) {
if (recoveryRaw !== null)
return "Some saved task data could not be read. Its original text is preserved in this browser.";
if (rejected.length > 0)
return "Some saved task records use an unsupported format. They are preserved in this browser.";
return "";
}
function loadVersionTwo(raw: string): TaskLoadResult {
try {
const saved: unknown = JSON.parse(raw);
if (
!isRecord(saved) ||
saved.version !== STORAGE_VERSION ||
!Array.isArray(saved.tasks) ||
!Array.isArray(saved.rejected) ||
!(saved.recoveryRaw === null || typeof saved.recoveryRaw === "string")
) {
throw new Error("Unsupported saved task format");
}
const split = splitTasks(saved.tasks);
const rejected = [...saved.rejected, ...split.rejected];
const recoveryRaw = saved.recoveryRaw;
return {
tasks: split.tasks,
rejected,
recoveryRaw,
warning: recoveryWarning(rejected, recoveryRaw),
shouldPersist: split.rejected.length > 0,
};
} catch {
return {
tasks: [],
rejected: [],
recoveryRaw: raw,
warning: recoveryWarning([], raw),
shouldPersist: true,
};
}
}
export function loadTasks(): TaskLoadResult {
try {
const current = localStorage.getItem(TASK_STORAGE_KEY);
if (current !== null) return loadVersionTwo(current);
const legacy = localStorage.getItem(LEGACY_TASK_STORAGE_KEY);
if (legacy === null) {
return {
tasks: [],
rejected: [],
recoveryRaw: null,
warning: "",
shouldPersist: false,
};
}
try {
const saved: unknown = JSON.parse(legacy);
if (!Array.isArray(saved))
throw new Error("Legacy tasks must be an array");
const split = splitTasks(saved);
return {
tasks: split.tasks,
rejected: split.rejected,
recoveryRaw: null,
warning: recoveryWarning(split.rejected, null),
shouldPersist: true,
};
} catch {
return {
tasks: [],
rejected: [],
recoveryRaw: legacy,
warning: recoveryWarning([], legacy),
shouldPersist: true,
};
}
} catch {
return {
tasks: [],
rejected: [],
recoveryRaw: null,
warning:
"Browser storage is unavailable. This session will not be saved.",
shouldPersist: false,
};
}
}
export function saveTasks(
tasks: Task[],
rejected: unknown[],
recoveryRaw: string | null,
) {
const saved: StoredTasks = {
version: STORAGE_VERSION,
tasks,
rejected,
recoveryRaw,
};
localStorage.setItem(TASK_STORAGE_KEY, JSON.stringify(saved));
}
export { recoveryWarning };
Build the app
Replace src/App.tsx with this component. The first render reads saved data once. If it finds version 1, it writes the migrated version 2 record after rendering and keeps the original version 1 key untouched as a backup.
import { useEffect, useState, type FormEvent } from "react";
import {
loadTasks,
recoveryWarning,
saveTasks,
type Task,
type TaskFilter,
} from "./task";
export default function App() {
const [initialLoad] = useState(loadTasks);
const [tasks, setTasks] = useState<Task[]>(initialLoad.tasks);
const [rejectedRecords] = useState(initialLoad.rejected);
const [recoveryRaw] = useState(initialLoad.recoveryRaw);
const [filter, setFilter] = useState<TaskFilter>("all");
const [title, setTitle] = useState("");
const [editingId, setEditingId] = useState<string | null>(null);
const [storageWarning, setStorageWarning] = useState(initialLoad.warning);
const [hasChanges, setHasChanges] = useState(initialLoad.shouldPersist);
useEffect(() => {
if (!hasChanges) return;
try {
saveTasks(tasks, rejectedRecords, recoveryRaw);
setStorageWarning(recoveryWarning(rejectedRecords, recoveryRaw));
} catch {
setStorageWarning("Changes may not be saved in this browser.");
console.warn("Task storage is unavailable");
}
}, [tasks, rejectedRecords, recoveryRaw, hasChanges]);
function updateTasks(updater: (current: Task[]) => Task[]) {
setTasks(updater);
setHasChanges(true);
}
const visible = tasks.filter(
(task) => filter === "all" || (filter === "done" ? task.done : !task.done),
);
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const cleanTitle = title.trim();
if (!cleanTitle) return;
if (editingId) {
updateTasks((current) =>
current.map((task) =>
task.id === editingId ? { ...task, title: cleanTitle } : task,
),
);
} else {
updateTasks((current) => [
...current,
{
id: crypto.randomUUID(),
title: cleanTitle,
done: false,
},
]);
}
setTitle("");
setEditingId(null);
}
return (
<main>
<h1>Task tracker</h1>
{storageWarning && <p role="status">{storageWarning}</p>}
<form onSubmit={submit}>
<label htmlFor="task-title">Task title</label>
<input
id="task-title"
value={title}
onChange={(event) => setTitle(event.currentTarget.value)}
/>
<button type="submit">{editingId ? "Save task" : "Add task"}</button>
</form>
<nav aria-label="Filter tasks">
{(["all", "active", "done"] as const).map((choice) => (
<button
key={choice}
type="button"
aria-pressed={filter === choice}
onClick={() => setFilter(choice)}
>
{choice}
</button>
))}
</nav>
{visible.length === 0 ? (
<p role="status">No tasks in this view.</p>
) : (
<ul>
{visible.map((task) => (
<li key={task.id}>
<label>
<input
type="checkbox"
checked={task.done}
onChange={() =>
updateTasks((current) =>
current.map((item) =>
item.id === task.id
? { ...item, done: !item.done }
: item,
),
)
}
/>
{task.title}
</label>
<button
type="button"
onClick={() => {
setEditingId(task.id);
setTitle(task.title);
}}
>
Edit {task.title}
</button>
</li>
))}
</ul>
)}
</main>
);
}
Labels name inputs, Enter submits, and aria-pressed marks the filter.
Choose where tasks live
This storage model fits a personal list that stays in one browser and can be rebuilt if the browser is cleared. Use an authenticated server when people need shared tasks, cross-device access, or access control.
Test behavior, then build
With the setup dependencies installed and jsdom configured in vite.config.ts, test an ordinary interaction and the version 1 migration. The legacy key should stay unchanged, and unsupported records should move into the version 2 envelope:
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import App from "./App";
import { TASK_STORAGE_KEY } from "./task";
beforeEach(() => {
localStorage.clear();
vi.stubGlobal("crypto", { randomUUID: () => "task-generated" });
});
afterEach(() => cleanup());
it("adds and toggles a task", async () => {
const user = userEvent.setup();
render(<App />);
await user.type(
screen.getByRole("textbox", { name: "Task title" }),
"Ship demo",
);
await user.click(screen.getByRole("button", { name: "Add task" }));
const task = screen.getByRole("checkbox", { name: "Ship demo" });
await user.click(task);
expect(task).toHaveProperty("checked", true);
});
it("migrates version 1 and preserves unsupported records", async () => {
const legacy = [
{ id: "task-1", title: "Read migration notes", done: false },
{ id: "task-2", title: "Old completion flag", done: 0 },
];
const legacyRaw = JSON.stringify(legacy);
localStorage.setItem("typed-task-tracker:v1", legacyRaw);
render(<App />);
await screen.findByRole("checkbox", { name: "Read migration notes" });
await waitFor(() => {
const raw = localStorage.getItem(TASK_STORAGE_KEY);
expect(raw).not.toBeNull();
expect(JSON.parse(raw!).version).toBe(2);
});
const migrated = JSON.parse(localStorage.getItem(TASK_STORAGE_KEY)!);
expect(migrated.tasks).toEqual([legacy[0]]);
expect(migrated.rejected).toEqual([legacy[1]]);
expect(localStorage.getItem("typed-task-tracker:v1")).toBe(legacyRaw);
expect(screen.getByRole("status").textContent).toMatch(/preserved/i);
});
Run the tests with npx vitest run. A production build checks that the app and TypeScript compile: in a Vite scaffold, run npm run build.
Task state flow
flowchart LR
A[Typed task state] --> B[Add or edit form]
A --> C[Filter and list]
C --> D[Toggle completion]
D --> A
A --> E[Validated local storage]
Trade-offs
| Choice | Good fit | Limitation |
|---|---|---|
| Local storage | One browser, offline personal draft | No account sync or access control |
| Server storage | Shared or multi-device tasks | Needs API and authentication |
| Small single component | Capstone or tiny screen | Harder to extend as features grow |
Failure cases to plan for
Legacy format failure mode: version 1 stored a bare task array, and some older records may contain values such as done: 0. The loader shows valid tasks, keeps unsupported records in the version 2 envelope, displays a recovery warning, and leaves the original version 1 key untouched. If the JSON cannot be parsed, version 2 stores the original text in recoveryRaw. Neither copy is cleared automatically.
If storage is full or blocked, setItem throws. The page keeps the current in-memory list and shows a save warning, but those edits may disappear on reload. A production app could offer a retry or export action.
Keep browser storage in its lane
The user and same-origin scripts can read or change local storage. Keep passwords, tokens, and sensitive shared records out of it. TypeScript checks code during development; it does not replace server-side validation or access control.
Common mistakes
Do not mutate task arrays, use array positions as keys, accept blank titles, or trust parsed JSON. One component is fine for this exercise. Split the form, list, or storage code once a piece needs its own behavior or tests.
Before you call it done
- Model filters as a union, not arbitrary strings.
- Use stable task IDs and immutable updates.
- Label controls and keep form submission keyboard-friendly.
- Validate persisted JSON before setting typed state; keep rejected values during migration.
- Use local storage only when browser-local persistence is enough.
If you add telemetry
- Count parse and write failures so storage problems are visible.
- Track add, edit, and toggle outcomes without sending task titles.
- Keep error messages useful and free of personal data.
Interview Questions
Task.
"all" | "active" | "done" lets TypeScript catch misspelled filter values before they reach the list logic.
- React can match the task between renders.
- Array positions change when the list is filtered or edited.
mapreplaces just the matching task.- Other tasks keep their existing values.
JSON.parse throws, so the loader catches the failure, preserves the original text, and shows a recovery warning.
- Valid JSON still needs a shape check.
- The migration leaves the original version 1 key as a backup.
- The input is associated with its label.
- Form submission works with both the button and the keyboard.
- Leave the current list visible and show a save warning.
- A larger app can add retry or export.
Further Reading
- Controlled inputs and forms covers accessible form state.
- Fetching and typing API data shows how to validate untrusted values.
- Component and interaction testing has more examples of testing visible behavior.
- React’s guide to updating arrays in state explains the immutable update pattern. MDN documents the browser’s localStorage API.
Conclusion
Local storage works for a personal list in one browser. Check every saved value before using it, keep the old version during migration, and show a warning when saving fails. Shared or cross-device tasks need a server.
Category
Related Posts
React + TypeScript Fundamentals Roadmap
Learn React and TypeScript through accessible, tested interfaces, from JSX and typed components to state, forms, effects, and a complete project.
Accessible React UI: Semantics, Labels, and Keyboard Use
Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.
Advanced React State: When Local State Stops Fitting
Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.