Skip to content

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:

Terminal window
npm install react-icons

Keep 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.

  1. Create src/AuthorDetails.tsx. The details component receives the selected author as item. IDetailsComponentProps<Author> gives it the generated row type. Use item.id to read that author’s books with BooksForAuthor.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 proxy
    const 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>
    );

    DataPage supplies 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 key remounts Books when 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.

  2. Create src/AddBook.tsx. Reuse it if the Arc tutorial already gave you this component. Like AddAuthor, 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 through initialValues:

    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 proxy
    export 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>
    );
    };

    authorId targets the selected author’s catalog. bookId is created once per dialog mount and remains stable while the title changes. Both must be present before validation can enable Add; assigning either in onBeforeExecute would be too late. In the next step, useDialog mounts this component for each operation and unmounts it on close, giving the next book a fresh id.

  3. Replace src/Authors.tsx with the list-and-detail screen. Keep it mounted in your existing application. DataPage reads AllAuthors, manages row selection, and opens the resizable pane when a row is selected. A menu command receives no row argument, so record the author through onSelectionChange and 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 proxy
    import { 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' }}>
    <DataPage
    title='Authors'
    query={AllAuthors}
    dataKey='id'
    emptyMessage='No authors yet'
    detailsComponent={AuthorDetails}
    onSelectionChange={(event) => setSelected(event.value)}
    >
    <DataPage.MenuItems>
    <MenuItem
    label='Add author'
    icon={FaPlus}
    command={() => void showAddAuthor()}
    />
    <MenuItem
    label='Add book'
    icon={FaBook}
    disableOnUnselected
    command={() => {
    if (selected) {
    void showAddBook({ authorId: selected.id });
    }
    }}
    />
    </DataPage.MenuItems>
    <DataPage.Columns>
    <Column field='name' header='Name' sortable />
    </DataPage.Columns>
    </DataPage>
    <AddAuthorWrapper />
    <AddBookWrapper />
    </div>
    );
    };

    DataPage owns selection here; onSelectionChange copies the current row into selected for 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.

  4. Try it. Add a book to one of your authors:

    1. With no selection, confirm that Add book is disabled.
    2. 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.
    3. Open Add book and enter a synthetic title such as Sample Book. Submit it. The dialog closes on command success; the title appears when BooksForAuthor delivers 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.
    4. 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.

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.

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.

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.