Loading, error and empty states
One screen with every state, end to end: useResource and useAction through a DataProvider, drawn with AsyncBlock and DataTable.
Every screen that talks to a server has four states for each thing it reads (loading, failed, empty, ready) and three for each thing it writes (sending, failed, done). BRICKS gives each of them a place, so a screen never shows a blank box or a stale number.
One screen, every state
Two reads (useResource) and one write (useAction) through a DataProvider. The seats card is drawn by AsyncBlock (skeleton, error with Try again, empty, data); the table takes the same resource's states as loading, error with onRetry, and empty. Invite shows pending on the button; the pretend server refuses about half the invites, and the refusal (invite.error, the server's sentence for a 422) shows as a Banner; a success says so in a toast. Pick what the pretend server answers next.
Code
import { useMemo, useState } from 'react';
import { AsyncBlock, Banner, Button, Card, DataProvider, DataTable, KeyValue, Note, PageGrid, Segmented, Skeleton, ToastRegion, createHttpClient, useAction, useResource, type DataColumn, type ToastMessage } from '@ergasti/bricks';
import { fakeApi } from './recipes';
interface Creator { id: number; name: string; orders: number }
interface Summary { creators: number; seats: number }
type Answer = 'ok' | 'empty' | 'fail';
const CREATORS: Creator[] = [{ id: 1, name: 'Laila Saeed', orders: 214 }, { id: 2, name: 'Karim Hosny', orders: 102 }, { id: 3, name: 'Salma Hosny', orders: 44 }];
function Screen({ answer, onInvited }: { answer: Answer; onInvited: (name: string) => void }) {
const summary = useResource<Summary>('/summary', { params: { answer } });
const list = useResource<{ rows: Creator[] }>('/creators', { params: { answer } });
const invite = useAction<{ id: number; name: string }, { ok: true }>({ method: 'POST', url: '/invites' }, { onDone: (_data, input) => onInvited(input.name) });
const columns: DataColumn<Creator>[] = [
{ key: 'name', label: 'Creator', primary: true, render: (c) => <b>{c.name}</b> },
{ key: 'orders', label: 'Orders', align: 'end', render: (c) => c.orders },
{ key: 'invite', label: 'Invite', align: 'end', render: (c) => <Button size="sm" disabled={invite.pending} onClick={() => void invite.run({ id: c.id, name: c.name })}>{invite.pending ? 'Sending…' : 'Invite again'}</Button> },
];
return (
<PageGrid>
<Card>
<Card.Header title="Seats" />
<AsyncBlock state={summary} skeleton={<Skeleton shape="rows" count={2} />} isEmpty={(s) => s.seats === 0} empty={<Note flush>No plan yet: seats show once the program starts.</Note>}>
{(s) => <KeyValue items={[{ label: 'Creators', value: s.creators }, { label: 'Seats', value: s.seats }]} />}
</AsyncBlock>
</Card>
{invite.error && <Banner tone="bad" action={<Button size="sm" onClick={invite.reset}>Dismiss</Button>}>{invite.error}</Banner>}
<DataTable
label="Creators" columns={columns} rowKey={(c) => c.id}
rows={list.data?.rows ?? []}
loading={list.status === 'loading'}
error={list.status === 'error' ? list.error?.message || 'The creators could not be loaded.' : null}
onRetry={list.reload}
empty={<Note flush>No creators yet. Invite some from Find creators.</Note>}
/>
</PageGrid>
);
}
function EndToEnd() {
const [answer, setAnswer] = useState<Answer>('ok');
const [toast, setToast] = useState<ToastMessage | null>(null);
const control = useMemo(() => ({ fail: false, delay: 900 }), []);
control.fail = answer === 'fail';
const client = useMemo(() => createHttpClient({
baseUrl: '/api',
fetch: fakeApi({
'GET /api/summary': () => (control.fail ? {} : { creators: answer === 'empty' ? 0 : 3, seats: answer === 'empty' ? 0 : 400 }),
'GET /api/creators': () => ({ rows: answer === 'empty' ? [] : CREATORS }),
'POST /api/invites': () => (Math.random() < 0.5 ? { ok: true } : { status: 422, body: { message: 'This creator was invited less than 24 hours ago.' } }),
}, control),
}), [answer, control]);
return (
<div style={{ display: 'grid', gap: 12 }}>
<Segmented label="Next answer" size="sm" value={answer} onChange={setAnswer} options={[['ok', 'Data'], ['empty', 'Empty'], ['fail', 'Error']]} />
<DataProvider client={client}>
<Screen answer={answer} onInvited={(name) => setToast({ message: `Invite sent to ${name}.` })} />
</DataProvider>
<ToastRegion toast={toast} onDismiss={() => setToast(null)} />
</div>
);
}Steps
- Give the screen a client. Make one client with createHttpClient and put it in a DataProvider above the screen. Every data hook below uses it.
- Read with
useResource.useResource(url, { params })returnsstatus(idle,loading,ready,error),data(kept while it reloads),errorandreload. See Load, page and save for paging and URL state. - Draw a block with
AsyncBlock. AsyncBlock takes the resource state and draws askeletonwhile loading, the error with a Retry button (wired toreload), youremptywhenisEmpty(data)says so, and the children with the data. - Draw a list with
DataTable's own states. DataTable takesloading(skeleton rows; existing rows stay while a later page loads),errorwithonRetry, andempty(oronClearFiltersfor the default "Nothing matches these filters" state). RowList and the blocks' lists take the same idea asstatus,errorandonRetry. - Write with
useAction.run(input)never throws on an HTTP failure: it resolves with the outcome. Usependingto lock the button (a second click sends nothing),errorfor a sentence in the viewer's language,fieldErrorsfor a form's 422, andonDoneto toast and reload. - Say the outcome. A success is a ToastRegion message; a failure the person must act on is a Banner or the form's own
error.
The same states, passed by hand
When your app has its own data layer, pass the states straight to the components:
The states without a server
The same components with the states passed by hand: what to show while loading, after an error and when there is nothing.
Code
import { DataTable, PageGrid, type DataColumn } from '@ergasti/bricks';
interface Creator { id: number; name: string; orders: number }
function ByHand() {
const columns: DataColumn<Creator>[] = [{ key: 'name', label: 'Creator', render: (c) => c.name }, { key: 'orders', label: 'Orders', align: 'end', render: (c) => c.orders }];
return (
<PageGrid>
<DataTable label="Loading" columns={columns} rows={[]} rowKey={(c) => c.id} loading loadingRows={2} />
<DataTable label="Failed" columns={columns} rows={[]} rowKey={(c) => c.id} error="The creators could not be loaded." onRetry={() => {}} />
<DataTable label="Nothing matches" columns={columns} rows={[]} rowKey={(c) => c.id} onClearFilters={() => {}} />
</PageGrid>
);
}Components with their own states
| Component | Loading | Error | Empty |
|---|---|---|---|
| DataTable | loading | error, onRetry | empty, onClearFilters |
| RowList | loading | error, onRetry | empty, emptyText |
| Leaderboard | loading | error, onRetry | empty |
| ActivityLog, MessageHistoryList, BundleGrid, GiftStockList, WalletLedger | status="loading" | status="error", error, onRetry | an empty list |
| FraudCaseDetail | loading | error, onRetry | no evidence given |
| Modal, Drawer | loading | your content | your content |
| Forms (GroupForm, ChallengeRequestForm, GiftProductsPicker, SpecialCommissionForm) | saving | error | |
| Dialogs (ReasonDialog, RecordGiftsDialog) | busy | error | |
| KeyValue, RankList, AuditLogList, HBars | none: check the length and show ListState, PrEmpty or EmptyView |
Related: useResource, useAction, AsyncBlock, Skeleton, ListState.