---
title: "Build your first feature: UI"
description: "Connect the authorized projects API to forms, a paginated list, detail and edit screens, cache refreshes, and account-switch cleanup."
url: "https://www.beignetjs.com/build-first-resource/ui"
markdown_url: "https://www.beignetjs.com/markdown/build-first-resource/ui.md"
framework_version: "0.0.65"
documentation_scope: "current-checkout"
source_revision: "ba3f49c103f3c4515e8ca14e07651fe5b83e2cec"
source_modified: true
---
# 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](https://www.beignetjs.com/markdown/build-first-resource/ownership.md), 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.
```typescript
// features/projects/client/queries.ts
import { 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](https://www.beignetjs.com/markdown/react-query.md#declarative-mutation-invalidation)
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`.
```tsx
// features/projects/components/project-list.tsx
"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 (
);
}
```
```tsx
// app/(app)/projects/page.tsx
import { ProjectList } from "@/features/projects/components/project-list";
export default function ProjectsPage() {
return ;
}
```
## 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.
```tsx
// features/projects/components/project-detail.tsx
"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
Loading project…
;
if (!project.data)
return (
{project.error?.message ?? "Could not load project."}
Back to projects
);
return (
{project.isError && (
Could not refresh this project. Your draft is still open.
{" "}{project.error.message}
If another tab changed this project, reload before saving again.
Reloading discards your unsaved edits.
{remove.isError &&
{remove.error.message}
}
);
}
```
```tsx
// app/(app)/projects/[id]/page.tsx
import { ProjectDetail } from "@/features/projects/components/project-detail";
export default async function ProjectPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return ;
}
```
## 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.
```diff
--- a/components/app-sidebar.tsx
+++ b/components/app-sidebar.tsx
@@ -1,4 +1,5 @@
"use client";
+import { useQueryClient } from "@tanstack/react-query";
import {
FileJsonIcon,
@@ -19,4 +20,5 @@
{ href: "/dashboard", label: "Dashboard", icon: LayoutDashboardIcon },
{ href: "/todos", label: "Todos", icon: ListTodoIcon },
+ { href: "/projects", label: "Projects", icon: ListTodoIcon },
{ href: "/settings", label: "Settings", icon: SettingsIcon },
];
@@ -36,7 +38,10 @@
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:
```bash
bun run format
bun beignet check
```
If 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
1. Open **Projects** in the sidebar, or visit
[the Projects page](http://localhost:3000/projects). The unowned rows from
chapter one are hidden, so an empty list is expected. Submit an empty name
and confirm that validation prevents it.
2. Create a project with a description. It appears without a page reload.
3. 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.
4. 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
1. Copy the project's detail URL. In a separate browser profile, create a
second account and open **Projects**. Its list should be empty.
2. Paste the first account's project URL into that profile. Access should be
denied. The ownership tests also cover attempted updates and deletes.
3. 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](https://www.beignetjs.com/markdown/deployment.md) |
| Add roles or sharing beyond individual ownership | [Authorization](https://www.beignetjs.com/markdown/authorization.md) |
| Test new application rules and UI behavior | [Testing](https://www.beignetjs.com/markdown/testing.md) |
| Learn durable background work, then apply it to Projects | [Run a background job](https://www.beignetjs.com/markdown/guides/background-jobs.md) |
For other features, `make resource` is the CRUD-shaped generator. Use
`bun beignet make feature ` for workflows, or add `--dry-run` to preview
the files a generator would write.