Skip to Content
BBRICKSv0.7.4
Recipes

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

  1. 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.
  2. Read with useResource. useResource(url, { params }) returns status (idle, loading, ready, error), data (kept while it reloads), error and reload. See Load, page and save for paging and URL state.
  3. Draw a block with AsyncBlock. AsyncBlock takes the resource state and draws a skeleton while loading, the error with a Retry button (wired to reload), your empty when isEmpty(data) says so, and the children with the data.
  4. Draw a list with DataTable's own states. DataTable takes loading (skeleton rows; existing rows stay while a later page loads), error with onRetry, and empty (or onClearFilters for the default "Nothing matches these filters" state). RowList and the blocks' lists take the same idea as status, error and onRetry.
  5. Write with useAction. run(input) never throws on an HTTP failure: it resolves with the outcome. Use pending to lock the button (a second click sends nothing), error for a sentence in the viewer's language, fieldErrors for a form's 422, and onDone to toast and reload.
  6. 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

ComponentLoadingErrorEmpty
DataTableloadingerror, onRetryempty, onClearFilters
RowListloadingerror, onRetryempty, emptyText
Leaderboardloadingerror, onRetryempty
ActivityLog, MessageHistoryList, BundleGrid, GiftStockList, WalletLedgerstatus="loading"status="error", error, onRetryan empty list
FraudCaseDetailloadingerror, onRetryno evidence given
Modal, Drawerloadingyour contentyour content
Forms (GroupForm, ChallengeRequestForm, GiftProductsPicker, SpecialCommissionForm)savingerror
Dialogs (ReasonDialog, RecordGiftsDialog)busyerror
KeyValue, RankList, AuditLogList, HBarsnone: check the length and show ListState, PrEmpty or EmptyView

Related: useResource, useAction, AsyncBlock, Skeleton, ListState.

On this page