Recipes
Sortable, filterable, paged list
A list screen wired to useListState and listFetcher: toolbar, table and pager.
A list screen is the same five pieces every time: a client, a fetcher that turns the list's query into a request, useListState that holds the query and the rows, a ListToolbar that edits the query, and a DataTable with a Pager that show the rows. This recipe puts them together.
The whole screen
KPI cards that filter, a toolbar (search, status chips, a tier select, sort with a flip button, reset, an action), a table sorted from its headers and a pager, all driven by one useListState over listFetcher. Try typing, sorting by a header, and filtering until nothing matches.
Code
import { useMemo } from 'react';
import { Button, CreatorCell, DataProvider, DataTable, KpiCard, KpiGrid, ListToolbar, Money, PageGrid, Pager, ScoreRing, TierChip, createHttpClient, listFetcher, useListState, type DataColumn } from '@ergasti/bricks';
import { creators, demoServer, type Creator } from './sample-data';
const PER_PAGE = 5;
const api = demoServer({
'GET /api/creators': ({ url }) => {
const get = (key: string) => url.searchParams.get(key) ?? '';
const sortKey = (get('sort') || 'sales') as 'name' | 'sales' | 'orders' | 'score';
const rows = creators
.filter((c) => (!get('q') || c.name.toLowerCase().includes(get('q').toLowerCase())) && (!get('status') || get('status') === 'all' || c.status.toLowerCase() === get('status')) && (!get('tier') || c.tier === get('tier')))
.sort((a, b) => ((a[sortKey] > b[sortKey] ? 1 : -1) * (get('dir') === 'asc' ? 1 : -1)));
const page = Number(get('page') || 1);
return { data: rows.slice((page - 1) * PER_PAGE, page * PER_PAGE), pagination: { total: rows.length, per_page: PER_PAGE, current_page: page, last_page: Math.max(1, Math.ceil(rows.length / PER_PAGE)) } };
},
}, 350);
const client = createHttpClient({ baseUrl: '/api', fetch: api });
const columns: DataColumn<Creator>[] = [
{ key: 'creator', label: 'Creator', sortKey: 'name', sortFirst: 'asc', render: (c) => <CreatorCell id={c.id} name={c.name} identity={c.identity} tier={c.tier} /> },
{ key: 'tier', label: 'Tier', render: (c) => <TierChip tier={c.tier} /> },
{ key: 'score', label: 'Score', sortKey: 'score', align: 'center', render: (c) => <ScoreRing value={c.score} /> },
{ key: 'orders', label: 'Orders', sortKey: 'orders', align: 'end', render: (c) => c.orders },
{ key: 'sales', label: 'Sales', sortKey: 'sales', align: 'end', render: (c) => <b><Money value={c.sales.toFixed(2)} compact /></b> },
];
function Creators() {
// One fetcher per client: listFetcher turns the list's query (q, chip, selects, sort, dir, page) into request params
// and the response into { rows, total, lastPage }.
const fetcher = useMemo(() => listFetcher<Creator>(client, '/creators', { chipParam: 'status' }), []);
const list = useListState<Creator>({
namespace: 'recipe-creators',
inHash: false, // the docs page keeps its own URL; in an app leave this on so reload, Back and shared links work
defaults: { chip: 'all', sort: 'sales', dir: 'desc', selects: { tier: '' } },
fetcher,
});
const filtered = list.query.q !== '' || list.query.chip !== 'all' || list.query.selects.tier !== '';
return (
<PageGrid>
<KpiGrid>
<KpiCard tone="lime" icon="user" label="Active" value="301" sub="In your program now" active={list.query.chip === 'active'} onClick={() => list.set({ chip: list.query.chip === 'active' ? 'all' : 'active' })} />
<KpiCard tone="butter" icon="pause" label="Paused" value="3" sub="Coupons stopped" active={list.query.chip === 'paused'} onClick={() => list.set({ chip: list.query.chip === 'paused' ? 'all' : 'paused' })} />
</KpiGrid>
<ListToolbar
search={{ value: list.query.q, onChange: (q) => list.set({ q }), placeholder: 'Search name or coupon' }}
chips={{ label: 'Status', value: list.query.chip, onChange: (chip) => list.set({ chip }), options: [{ value: 'all', label: 'All' }, { value: 'active', label: 'Active' }, { value: 'paused', label: 'Paused' }, { value: 'removed', label: 'Removed' }] }}
selects={[{ id: 'tier', label: 'Tier', value: list.query.selects.tier, onChange: (tier) => list.set({ selects: { tier } }), options: [['', 'All tiers'], ['rising', 'Rising'], ['established', 'Established'], ['elite', 'Elite']] }]}
sort={{
value: list.query.sort, dir: list.query.dir,
options: [['sales', 'Sales', 'desc'], ['orders', 'Orders', 'desc'], ['score', 'Score', 'desc'], ['name', 'Name (A–Z)', 'asc']],
onChange: (sort, dir) => list.set({ sort, ...(dir ? { dir } : {}) }),
onFlip: () => list.set({ dir: list.query.dir === 'asc' ? 'desc' : 'asc' }),
}}
reset={{ active: filtered, onReset: list.reset }}
actions={<Button size="sm">Export CSV</Button>}
/>
<DataTable
label="Creators"
columns={columns}
rows={list.rows}
rowKey={(c) => c.id}
loading={list.loading}
error={list.error ? list.error.message || 'We could not load the creators.' : undefined}
onRetry={list.retry}
onClearFilters={list.reset}
isDim={(c) => c.status === 'Removed'}
sort={{ key: list.query.sort, dir: list.query.dir }}
onSort={(s) => list.set({ sort: s.key, dir: s.dir })}
footer={<Pager page={list.page} lastPage={list.lastPage} total={list.total} perPage={PER_PAGE} loading={list.loading} label="Creators" onPage={(page) => list.set({ page })} />}
/>
</PageGrid>
);
}
function Screen() {
return (
<DataProvider client={client}>
<Creators />
</DataProvider>
);
}How it fits together
createHttpClientmakes the client once, andDataProviderhands it down. Here itsfetchis a pretend server so the page works offline; in an app you passbaseUrlandonUnauthorized.listFetcher(client, '/creators', { chipParam: 'status' })returns the(query, signal) => Promise<ListPage>thatuseListStatewants. It sendsq,sort,dir,page, each select by its id, and the chip asstatus, and reads the response with theautoadapter (pagination, Laravel'smeta, a bare paginator or an array). Memoise it on the client.useListStatekeepsq,chip, selects,sort,dirandpageunder anamespace. WithinHashon (the default) they live in the URL hash, so reload, Back and a shared link land on the same view. Any filter or sort change returns to page 1, every change aborts the request before it, and a page that empties steps back to the new last page.defaultsare never written to the URL.ListToolbaris controlled bylist.queryand edits it withlist.set(patch). Itsresetshows only while a filter is set;list.resetclears everything back to the defaults.DataTabletakessortandonSort, which map tolist.query.sortanddir. Give each sortable column asortKeyand setsortFirst: 'asc'on name columns, because the first click sorts high to low otherwise.- Loading, empty and error are props on the table:
loadingdraws skeleton rows, an emptyrowsdraws the empty text with a "Clear filters" button (onClearFilters), anderrorplusonRetrydraw the failure. Pagergoes in the table'sfooter. WithperPageit says "Showing 1–5 of 12";list.set({ page })is its handler.
Things to know
- Pass
inHash: falseonly when the URL must not change (this docs page; a modal list). - Two lists on one screen need two
namespaces. - The row type comes from your fetcher:
useListState<Creator>andlistFetcher<Creator>agree on it. - For a phone,
DataTableturns rows into cards by itself (mode="cards"forces it,renderCardcustomises it).
Related: useListState, listFetcher, ListToolbar, DataTable, Pager.