Build your first feature: UI
Chapter 3 of 3. Connect your Projects API to a create form, paginated list,
and detail/edit screen.
By the end, you can use the feature at /projects, recover from conflicting
edits, and switch accounts without retaining another user's cached data.
Before you start
Finish 2. Add ownership, with its migrations
applied, access tests passing, and bun beignet check passing. Continue in the
same app. Keep the starter's authenticated layout, Query Client provider, and
form helpers; no additional packages are needed.
Create the files shown in each explorer. Select a file to read and copy its complete source, and create any missing directories.
| Files | Change |
|---|---|
features/projects/client/queries.ts | Share pagination and mutation refresh rules |
features/projects/components/project-list.tsx | Display projects and create new ones |
features/projects/components/project-detail.tsx | Read, edit, and delete a project |
app/(app)/projects/page.tsx and app/(app)/projects/[id]/page.tsx | Mount both screens in the authenticated layout |
components/app-sidebar.tsx | Add navigation and clear cached data on sign-out |
Connect queries and mutations
The starter exports rq for typed TanStack Query options and rhf for forms
validated against contract schemas. Use those existing helpers for Projects.
Create features/projects/client/queries.ts. Creating refreshes lists; updating or
deleting also refreshes that project's detail query. The detail component can
pass rq(getProject).queryOptions(...) directly to useQuery.
Sharing these options keeps the pagination and refresh rules together while the components handle what users see.
1234567891011121314151617181920212223242526272829303132333435363738394041import { cursorPagination } from "@beignet/react-query";import { rq } from "@/client";import { createProject, deleteProject, getProject, listProjects, updateProject,} from "../contracts";
export function projectsQueryOptions() { return rq(listProjects).infiniteQueryOptions({ query: { limit: 20 }, ...cursorPagination(), });}
export function createProjectMutationOptions() { return rq(createProject).mutationOptions({ invalidates: () => [rq(listProjects).contractFilter()], });}
export function updateProjectMutationOptions() { return rq(updateProject).mutationOptions({ invalidates: (_project, variables) => [ rq(listProjects).contractFilter(), rq(getProject).filter({ path: variables.path }), ], });}
export function deleteProjectMutationOptions() { return rq(deleteProject).mutationOptions({ invalidates: (_result, variables) => [ rq(listProjects).contractFilter(), rq(getProject).filter({ path: variables.path }), ], });}
These are ordinary TanStack Query options. invalidates marks matching queries
stale and refetches active queries. Beignet awaits that work before
mutateAsync() resolves. Keep lifecycle callbacks inside mutationOptions
when adding them; replacing its returned onSuccess would replace the
invalidation behavior. See React Query
for the full API.
Build the projects list
Create features/projects/components/project-list.tsx. The form uses the
create contract's schema, displays validation and request errors, and resets
after a successful create. Fields are read-only until the request and cache
invalidations finish, so that reset cannot erase edits made during submission.
The list includes loading, empty, retry, and load-more states. Expose it under
the starter's authenticated layout with app/(app)/projects/page.tsx.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"use client";
import { useInfiniteQuery, useMutation } from "@tanstack/react-query";import Link from "next/link";import { rhf } from "@/client/forms";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { createProjectMutationOptions, projectsQueryOptions,} from "../client/queries";import { createProject } from "../contracts";
export function ProjectList() { const projects = useInfiniteQuery(projectsQueryOptions()); const create = useMutation(createProjectMutationOptions()); const form = rhf(createProject).useForm({ defaultValues: { name: "", description: "" }, }); const submit = form.handleSubmit(async (body) => { form.clearErrors("root"); try { await create.mutateAsync({ body }); form.reset(); } catch (error) { form.setError("root", { message: error instanceof Error ? error.message : "Could not create project.", }); } });
return ( <div className="space-y-8"> <h1 className="text-2xl font-semibold">Projects</h1> <form onSubmit={submit} className="space-y-4"> <div className="space-y-2"> <Label htmlFor="project-name">Name</Label> <Input id="project-name" readOnly={form.formState.isSubmitting} {...form.register("name")} /> <p role="alert">{form.formState.errors.name?.message}</p> </div> <div className="space-y-2"> <Label htmlFor="project-description">Description</Label> <Input id="project-description" readOnly={form.formState.isSubmitting} {...form.register("description")} /> <p role="alert">{form.formState.errors.description?.message}</p> </div> <p role="alert">{form.formState.errors.root?.message}</p> <Button type="submit" disabled={form.formState.isSubmitting}> {form.formState.isSubmitting ? "Creating…" : "Create project"} </Button> </form> <section aria-label="Your projects" className="space-y-4"> {projects.isPending && <p>Loading projects…</p>} {projects.isError && ( <div role="alert"> <p>{projects.error.message}</p> <Button type="button" onClick={() => void projects.refetch()}> Try again </Button> </div> )} {projects.data?.pages.every((page) => page.items.length === 0) && ( <p>No projects yet. Create your first one above.</p> )} <ul className="space-y-3"> {projects.data?.pages .flatMap((page) => page.items) .map((project) => ( <li key={project.id}> <Link className="underline" href={`/projects/${project.id}`}> {project.name} </Link> <p className="text-sm text-muted-foreground"> {project.description} </p> </li> ))} </ul> {projects.hasNextPage && ( <Button type="button" disabled={projects.isFetchingNextPage} onClick={() => void projects.fetchNextPage()} > {projects.isFetchingNextPage ? "Loading…" : "Load more"} </Button> )} </section> </div> );}
Add the detail and edit screen
Each project has a version. Saving sends the version that was loaded; if
someone else has saved since then, the API rejects the outdated write with
PROJECT_CONFLICT. This prevents one edit from silently overwriting another.
Create features/projects/components/project-detail.tsx. The edit form carries
the version it loaded and sends that version with the write. A background
refetch updates an untouched form when a newer version arrives. Once the user
starts editing, preserve the whole draft and its version until they save or
reload. Fields are read-only while saving or deleting.
After a successful save, reset the form to the saved response, including its new version. Only accept newer versions from background refreshes, so an older cached response cannot undo that reset if a refresh fails.
If another tab writes first, the server rejects the stale edit. The user can
reload the current project and try again. Deletion asks for confirmation and
returns to the list after the request and invalidations complete. Add the dynamic
route at app/(app)/projects/[id]/page.tsx to pass the project ID to the screen.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157"use client";
import { useMutation, useQuery } from "@tanstack/react-query";import Link from "next/link";import { useRouter } from "next/navigation";import { useEffect } from "react";import { rq } from "@/client";import { rhf } from "@/client/forms";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { deleteProjectMutationOptions, updateProjectMutationOptions,} from "../client/queries";import { getProject, updateProject } from "../contracts";import type { Project } from "../schemas";
export function ProjectDetail({ id }: { id: string }) { const project = useQuery(rq(getProject).queryOptions({ path: { id } })); if (project.isPending) return <p>Loading project…</p>; if (!project.data) return ( <div role="alert"> <p>{project.error?.message ?? "Could not load project."}</p> <Button type="button" onClick={() => void project.refetch()}> Try again </Button> <Link href="/projects">Back to projects</Link> </div> ); return ( <div className="space-y-4"> {project.isError && ( <p role="alert"> Could not refresh this project. Your draft is still open. {" "}{project.error.message} </p> )} <ProjectEditor key={id} project={project.data} /> </div> );}
function ProjectEditor({ project }: { project: Project }) { const router = useRouter(); const update = useMutation(updateProjectMutationOptions()); const remove = useMutation(deleteProjectMutationOptions()); const form = rhf(updateProject).useForm({ defaultValues: { name: project.name, description: project.description ?? "", version: project.version, }, }); const { isDirty, isSubmitting } = form.formState; const { getValues, reset } = form; const busy = isSubmitting || remove.isPending; useEffect(() => { if (!isDirty && !busy && project.version > getValues("version")) { reset({ name: project.name, description: project.description ?? "", version: project.version, }); } }, [busy, getValues, isDirty, project, reset]); const submit = form.handleSubmit(async (body) => { form.clearErrors("root"); try { const saved = await update.mutateAsync({ path: { id: project.id }, body, }); form.reset({ name: saved.name, description: saved.description ?? "", version: saved.version, }); } catch (error) { form.setError("root", { message: error instanceof Error ? error.message : "Could not save project.", }); } }); async function deleteCurrentProject() { if (!window.confirm("Delete this project?")) return; try { await remove.mutateAsync({ path: { id: project.id } }); router.push("/projects"); } catch { // The mutation error is rendered below; keep the current page open. } }
return ( <div className="space-y-6"> <Link href="/projects" className="underline"> Back to projects </Link> <h1 className="text-2xl font-semibold">Edit project</h1> <form onSubmit={submit} className="space-y-4"> <input type="hidden" {...form.register("version", { valueAsNumber: true })} /> <div className="space-y-2"> <Label htmlFor="project-name">Name</Label> <Input id="project-name" readOnly={busy} {...form.register("name")} /> <p role="alert">{form.formState.errors.name?.message}</p> </div> <div className="space-y-2"> <Label htmlFor="project-description">Description</Label> <Input id="project-description" readOnly={busy} {...form.register("description")} /> <p role="alert">{form.formState.errors.description?.message}</p> </div> <p role="alert">{form.formState.errors.root?.message}</p> <Button type="submit" disabled={busy}> {form.formState.isSubmitting ? "Saving…" : "Save project"} </Button> </form> <p className="text-sm text-muted-foreground"> If another tab changed this project, reload before saving again. Reloading discards your unsaved edits. </p> <Button type="button" variant="outline" disabled={busy} onClick={() => window.location.reload()} > Reload project </Button> <div> <Button type="button" variant="destructive" disabled={busy} onClick={() => void deleteCurrentProject()} > {remove.isPending ? "Deleting…" : "Delete project"} </Button> {remove.isError && <p role="alert">{remove.error.message}</p>} </div> </div> );}
Add navigation and clear data on sign-out
Add Projects to the sidebar. Also cancel active queries and clear the Query Client when signing out. The project responses depend on the session cookie, which is deliberately excluded from generated query keys; keeping cached data across account changes could show the previous user's list.
1234514 unmodified lines202122232413 unmodified lines38394041424344454647"use client";
import { useQueryClient } from "@tanstack/react-query";import { FileJsonIcon,14 unmodified lines { href: "/dashboard", label: "Dashboard", icon: LayoutDashboardIcon }, { href: "/todos", label: "Todos", icon: ListTodoIcon }, { href: "/projects", label: "Projects", icon: ListTodoIcon }, { href: "/settings", label: "Settings", icon: SettingsIcon },];13 unmodified lines const pathname = usePathname(); const router = useRouter(); const queryClient = useQueryClient();
async function signOut() { await authClient.signOut(); await queryClient.cancelQueries(); queryClient.clear(); router.push("/"); router.refresh();For other ways of switching accounts, apply the same cache-reset rule at that identity change. Authorization on the server remains required regardless of what is cached in the browser.
Try the complete feature
Format the new files and run the app checks:
bun run format
bun beignet checkIf the development server is stopped, start it in your other terminal with
bun run dev. Sign in with the account you created in the quickstart.
Create, edit, and delete a project
- Open Projects in the sidebar, or visit the Projects page. The unowned rows from chapter one are hidden, so an empty list is expected. Submit an empty name and confirm that validation prevents it.
- Create a project with a description. It appears without a page reload.
- Open its detail page, edit the name and description, and save. Return to the list and confirm it shows the new values. Reload the browser to verify persistence.
- Delete the project and confirm the prompt. You return to the list, where it is gone. Refreshing its old detail URL returns a not-found error.
Create another project and keep it for the next two checks.
Recover from a conflicting edit
Open that project in two tabs and change the name in both tabs before saving either one. Save the first tab, then submit the second tab's draft. The second save should report a conflict and preserve its unsaved draft.
Use Reload project in the second tab. It discards that draft and loads the saved values and version. You can edit and save again. When a form has no unsaved edits, a background refresh can update its fields and version together.
Check account isolation
- Copy the project's detail URL. In a separate browser profile, create a second account and open Projects. Its list should be empty.
- Paste the first account's project URL into that profile. Access should be denied. The ownership tests also cover attempted updates and deletes.
- In the original profile, sign out through the sidebar and sign in as the second account. The first account's projects must not appear from the cache, even briefly. This checks the sign-out cleanup you added above.
Checkpoint: a complete feature
You can create, list, edit, and delete projects through the UI. Descriptions persist, another account cannot access the data, and an outdated edit cannot overwrite a newer one. The app checks and the browser checks above should pass.
The feature follows the same path as Todos: a contract supplies validation and client types, a use case enforces the application's rules, and a port connects it to storage. The UI consumes that contract and refreshes affected queries after writes.
Where to go next
Choose a guide for the next thing your application needs:
| Goal | Guide |
|---|---|
| Prepare this app for a hosted environment | Going to production |
| Add roles or sharing beyond individual ownership | Authorization |
| Test new application rules and UI behavior | Testing |
| Learn durable background work, then apply it to Projects | Run a background job |
For other features, make resource is the CRUD-shaped generator. Use
bun beignet make feature <name> for workflows, or add --dry-run to preview
the files a generator would write.