3. Cratis Components: Show an author's books
Use DataPage in Cratis Components to select an author, read their books beside the list, and add a title to that author’s catalog. You will replace the table-and-button screen with a list, an action bar, and a resizable details pane. The selected author’s id connects the books query to the add-book command.
Continue from Act on the list, with the backend running and the providers and CSS still in place. Keep src/AddAuthor.tsx and the generated author proxies. Complete the backend steps in Arc’s Relate your slices before starting: you need src/Books/Book.ts, which exports BooksForAuthor, and src/Books/AddBook.ts, which exports AddBook. Regenerate the proxies if either file is missing. These imports are generated classes used at runtime, not type-only declarations.
The final screen imports icons directly. Declare react-icons in your frontend package so your imports resolve with strict package managers, even though Components also depends on it internally:
npm install react-iconsKeep the selected Author.id as a generated Guid value for both BooksForAuthor’s authorId argument and AddBook’s authorId value. Create a separate bookId for each new book. String(...) in the examples supplies React keys; it does not convert the ids sent to the query or command.
-
Create
src/AuthorDetails.tsx. The details component receives the selected author asitem.IDetailsComponentProps<Author>gives it the generated row type. Useitem.idto read that author’s books withBooksForAuthor.use({ authorId }); the hook takes an argument object, not a positional id:src/AuthorDetails.tsx import type { Guid } from '@cratis/fundamentals';import type { IDetailsComponentProps } from '@cratis/components/DataPage';import type { Author } from './Authors/Author';import { BooksForAuthor } from './Books/Book'; // generated observable query proxyconst Books = ({ authorId }: { authorId: Guid }) => {const [books] = BooksForAuthor.use({ authorId });if (!books.isAuthorized) return <p role='alert'>You cannot view these books.</p>;const isLoading = books.isPerforming || books.isReady === false;if (books.hasExceptions || books.isValid === false || (!isLoading && books.isSuccess === false)) {return <p role='alert'>Could not load books.</p>;}if (isLoading && !books.hasData) return <p>Loading books…</p>;if (books.data.length === 0) return <p>No books yet.</p>;return (<ul>{books.data.map((book) => (<li key={String(book.id)}>{book.title}</li>))}</ul>);};export const AuthorDetails = ({ item }: IDetailsComponentProps<Author>) => (<section aria-label={`Books by ${item.name}`}><h2>{item.name}</h2><Books key={String(item.id)} authorId={item.id} /></section>);DataPagesupplies the author, but it does not fetch related books. This component owns a separate observable query and must distinguish its empty result from a pending, failed, or unauthorized one. The branches check denied access first, then exceptions or invalid arguments. A performing or not-ready query stays in loading state; once loading ends, an unsuccessful result is a failure even if it carries no exception. A successful empty list shows No books yet. Existing books remain visible during a refresh.The
keyremountsBookswhen the selected author’s id changes, so the previous author’s component state does not carry into the new selection. If the new author’s result is already available, it can appear immediately; otherwise expect Loading books…. Later results from that author’s query update the list while the pane is open. -
Create
src/AddBook.tsx. Reuse it if the Arc tutorial already gave you this component. LikeAddAuthor, the dialog collects one visible value, here the book title. It also needs two required values with no input fields: the selected author’s id and the new book’s id. Supply both throughinitialValues:src/AddBook.tsx import { useState } from 'react';import { Guid } from '@cratis/fundamentals';import { CommandDialog } from '@cratis/components/CommandDialog';import { InputTextField } from '@cratis/components/CommandForm';import { AddBook } from './Books/AddBook'; // generated proxyexport const AddBookDialog = ({ authorId }: { authorId: Guid }) => {const [bookId] = useState(() => Guid.create());return (<CommandDialog<AddBook>command={AddBook}title='Add book'okLabel='Add'initialValues={{ authorId, bookId }}><InputTextField<AddBook> value={(command) => command.title} title='Title' /></CommandDialog>);};authorIdtargets the selected author’s catalog.bookIdis created once per dialog mount and remains stable while the title changes. Both must be present before validation can enable Add; assigning either inonBeforeExecutewould be too late. In the next step,useDialogmounts this component for each operation and unmounts it on close, giving the next book a fresh id. -
Replace
src/Authors.tsxwith the list-and-detail screen. Keep it mounted in your existing application.DataPagereadsAllAuthors, manages row selection, and opens the resizable pane when a row is selected. A menu command receives no row argument, so record the author throughonSelectionChangeand read that state when Add book runs:src/Authors.tsx import { useState } from 'react';import { useDialog } from '@cratis/arc.react/dialogs';import { Column, DataPage, MenuItem } from '@cratis/components/DataPage';import { FaBook, FaPlus } from 'react-icons/fa6';import { AllAuthors, type Author } from './Authors/Author'; // generated proxyimport { AddAuthor } from './AddAuthor';import { AddBookDialog } from './AddBook';import { AuthorDetails } from './AuthorDetails';export const Authors = () => {const [selected, setSelected] = useState<Author | null>(null);const [AddAuthorWrapper, showAddAuthor] = useDialog(AddAuthor);const [AddBookWrapper, showAddBook] = useDialog(AddBookDialog);return (<div style={{ height: '100vh' }}><DataPagetitle='Authors'query={AllAuthors}dataKey='id'emptyMessage='No authors yet'detailsComponent={AuthorDetails}onSelectionChange={(event) => setSelected(event.value)}><DataPage.MenuItems><MenuItemlabel='Add author'icon={FaPlus}command={() => void showAddAuthor()}/><MenuItemlabel='Add book'icon={FaBook}disableOnUnselectedcommand={() => {if (selected) {void showAddBook({ authorId: selected.id });}}}/></DataPage.MenuItems><DataPage.Columns><Column field='name' header='Name' sortable /></DataPage.Columns></DataPage><AddAuthorWrapper /><AddBookWrapper /></div>);};DataPageowns selection here;onSelectionChangecopies the current row intoselectedfor the action without making selection controlled.dataKey='id'matches rows by the author’s stable, unique id when a ready result replaces them with new objects. If that author is no longer in the returned page, selection can clear. The pane then closes and Add book disables until you select an available author.Both dialog wrappers sit outside
DataPage, so opening a dialog does not depend on the details pane staying mounted.showAddBook({ authorId: selected.id })supplies the author chosen when the action runs. -
Try it. Add a book to one of your authors:
- With no selection, confirm that Add book is disabled.
- Select an author. Check that the action enables and the right-hand heading names that author. Wait for the books query to show their titles or a successful No books yet. result.
- Open Add book and enter a synthetic title such as Sample Book. Submit it. The dialog closes on command success; the title appears when
BooksForAuthordelivers a result containing it. These are separate checkpoints. Add a second book through a new dialog and inspect the query data to check that its id differs from the first. - Select a different author. Their heading and books should replace the previous selection’s content, and the titles you just added should remain with the first author. If the new result is pending, expect a loading message. Drag the divider with a pointer to check the available space.
BooksForAuthor filters on the server, so the pane receives the selected author’s catalog instead of loading every book and filtering in the browser. The author table and books pane can use different read models, each shaped for what it displays. For a Chronicle-backed application, see Read Models.
Check the selection handoff
Section titled “Check the selection handoff”| Value | Comes from | Goes to |
|---|---|---|
selected |
onSelectionChange(event).value |
The no-argument MenuItem.command closure |
authorId |
selected.id when Add book runs |
showAddBook({ authorId }), then initialValues |
bookId |
Guid.create() on each dialog mount |
AddBook.initialValues |
| Books query argument | The details component’s item.id |
BooksForAuthor.use({ authorId }) |
disableOnUnselected controls action availability; it does not pass a row into the callback. Keep the if (selected) guard and selection state. The backend must still authorize the command and validate its current target; a visible author or enabled action grants no permission. Here the typed AuthorDetails supplies row-type inference; without a typed details component, use explicit DataPage generics as in the list-screen recipe.
If Add stays disabled after entering a title, check initialValues for both authorId and bookId, then follow CommandDialog validation. If books appear under the wrong name, compare selected.id, item.id, the query’s authorId, and the displayed result. A detail panel shows the previous author’s books walks through that mismatch. For a collapsed layout, check the definite-height prerequisite above.
Look back at what you built
Section titled “Look back at what you built”You can register an author, select them, and add books to their catalog without leaving the library screen. DataPage connects the author list to the details pane; your code passes the selected id explicitly to the books query and add-book dialog. Command completion and updated query results remain separate signals, so you can diagnose a failed write without confusing it with a stale list.
Reuse that pattern for another related view: start with a query-backed list, decide which id the next query or command needs, and supply it before opening the form. Field accessors and row-property access are typed against generated contracts. Column.field remains a plain string that you must keep aligned with the read model.
Where to go next
Section titled “Where to go next”To adapt the right-hand view, start with Details Panel for related-data loading, sizing, and narrow-screen alternatives. When adding another selection-aware action, use Accessing Selected Item for reading the selected row in your handler and keeping the null guard.
When the next task is to collect more book information, continue with Building a form to choose fields and handle command values.
Before reusing the screen, check it with a keyboard: reach the actions, select an author, open a dialog, identify its title and field labels, then cancel and check where focus returns. Check a rejected command’s visible field messages too. These application checks do not establish accessibility conformance. Use Troubleshooting for connection, styling, validity, and layout failures.