Skip to Content
BBRICKSv0.7.4
DataOverview

Load, page and save

A guide to the data hooks: load a resource, page a list, save with field errors.

Three jobs cover most screens: load something, page through a list, save a change. Each has a hook, and all of them take their HTTP client from the nearest DataProvider.

Load: useResource

useResource(url, { params }) does a GET and returns a ResourceState: status (idle, loading, ready, error), data (kept while it reloads), error and reload. A new params aborts the request in flight and a late reply is ignored. Pass null as the URL (or enabled: false) to wait. Draw the states with AsyncBlock:

useResource(url, { params }) returns ResourceState (idle, loading, ready, error) with data kept while it reloads. A new params aborts the request in flight and a late reply is ignored. AsyncBlock draws the states.

Code
import { useState } from 'react';
import { AsyncBlock, DataProvider, Skeleton, createHttpClient, useResource } from '@ergasti/bricks';
import { demoServer } from './sample-data';

const client = createHttpClient({
  baseUrl: '/api',
  fetch: demoServer({
    'GET /api/creators': ({ url }) => ({ rows: ['Laila Saeed', 'Karim Hosny', 'Salma Hosny'].filter((n) => n.toLowerCase().includes((url.searchParams.get('q') ?? '').toLowerCase())) }),
    'GET /api/broken': () => ({ status: 500, body: {} }),
  }),
});

function Creators({ q }: { q: string }) {
  const creators = useResource<{ rows: string[] }>('/creators', { params: { q } });
  return (
    <AsyncBlock state={creators} skeleton={<Skeleton shape="rows" count={2} />} isEmpty={(data) => data.rows.length === 0} empty="Nobody matches">
      {(data) => <ul>{data.rows.map((name) => <li key={name}>{name}</li>)}</ul>}
    </AsyncBlock>
  );
}

function Search() {
  const [q, setQ] = useState('');
  return (
    <DataProvider client={client}>
      <input aria-label="Filter creators" placeholder="Try “sal”" value={q} onChange={(e) => setQ(e.target.value)} />
      <Creators q={q} />
    </DataProvider>
  );
}

When it fails, the error carries the status and the server's viewer-facing message, and reload retries:

A failed read

The error carries the HTTP status and, for 422s and business refusals, the server's message; reload retries.

Code
import { AsyncBlock, DataProvider, Skeleton, createHttpClient, useResource } from '@ergasti/bricks';
import { demoServer } from './sample-data';

const client = createHttpClient({
  baseUrl: '/api',
  fetch: demoServer({
    'GET /api/creators': ({ url }) => ({ rows: ['Laila Saeed', 'Karim Hosny', 'Salma Hosny'].filter((n) => n.toLowerCase().includes((url.searchParams.get('q') ?? '').toLowerCase())) }),
    'GET /api/broken': () => ({ status: 500, body: {} }),
  }),
});

function Broken() {
  const broken = useResource<unknown>('/broken');
  return <AsyncBlock state={broken} skeleton={<Skeleton shape="line" />}>{() => null}</AsyncBlock>;
}

function Failure() {
  return <DataProvider client={client}><Broken /></DataProvider>;
}

Page: usePaged and useListState

usePaged(url, { params }) reads a paginated GET and returns rows, page, lastPage, total, a summary and setPage. It understands pagination, Laravel's meta, a bare paginator or an array (the adapter option, 'auto' by default), keeps the rows while the next page loads, goes back to page 1 when params change and steps back when the last page empties.

A paged list

usePaged reads a paginated GET (it understands pagination, Laravel's meta, a bare paginator or an array), keeps the rows while the next page loads, and goes back to page 1 when params change.

Code
import { DataProvider, Pager, createHttpClient, usePaged } from '@ergasti/bricks';
import { demoServer } from './sample-data';

const NAMES = Array.from({ length: 47 }, (_, i) => `Creator ${i + 1}`);

const client = createHttpClient({
  baseUrl: '/api',
  fetch: demoServer({
    'GET /api/creators': ({ url }) => {
      const page = Number(url.searchParams.get('page') ?? 1);
      const start = (page - 1) * 10;
      return { data: NAMES.slice(start, start + 10), pagination: { total: NAMES.length, per_page: 10, current_page: page, last_page: Math.ceil(NAMES.length / 10) } };
    },
  }, 300),
});

function List() {
  const list = usePaged<string, never>('/creators', { perPage: 10 });
  return (
    <div>
      <ul>{list.rows.map((name) => <li key={name}>{name}</li>)}</ul>
      <Pager page={list.page} lastPage={list.lastPage} total={list.total} perPage={10} loading={list.status === 'loading'} label="Creators" onPage={list.setPage} />
    </div>
  );
}

function Paged() {
  return <DataProvider client={client}><List /></DataProvider>;
}

For a whole list screen (search, status chips, selects, sort, page, all in the URL) use useListState, with a fetcher from listFetcher:

const fetcher = useMemo(() => listFetcher<Creator>(client, '/creators', { chipParam: 'status' }), [client]);
const list = useListState({ namespace: 'cr', defaults: { selects: { tier: '' } }, fetcher });
// list.rows, list.page, list.lastPage, list.total, list.loading, list.error, list.set(patch), list.reset(), list.retry()

One list's state

Search, chip, selects, sort and page live in the URL hash under namespace (here inHash: false keeps this docs page's URL clean); any filter or sort change goes back to page 1, each change aborts the previous request, and an emptied last page steps back.

Code
import { Button, DataTable, ListToolbar, Pager, useListState, type DataColumn, type ListPage, type ListQuery } from '@ergasti/bricks';
import { creators, type Creator } from './sample-data';

const serve = async (q: ListQuery): Promise<ListPage<Creator>> => {
  await new Promise((resolve) => window.setTimeout(resolve, 300));
  const rows = creators.filter((c) => (!q.q || c.name.toLowerCase().includes(q.q.toLowerCase())) && (!q.chip || q.chip === 'all' || c.status.toLowerCase() === q.chip));
  const sorted = [...rows].sort((a, b) => {
    const [x, y] = q.sort === 'name' ? [a.name, b.name] : [a.sales, b.sales];
    return (x > y ? 1 : x < y ? -1 : 0) * (q.dir === 'asc' ? 1 : -1);
  });
  return { rows: sorted.slice((q.page - 1) * 5, q.page * 5), total: rows.length, lastPage: Math.max(1, Math.ceil(rows.length / 5)) };
};

const columns: DataColumn<Creator>[] = [
  { key: 'name', label: 'Creator', sortKey: 'name', sortFirst: 'asc', render: (c) => c.name },
  { key: 'status', label: 'Status', render: (c) => c.status },
  { key: 'sales', label: 'Sales', sortKey: 'sales', align: 'end', render: (c) => c.sales.toLocaleString('en-US') },
];

function Creators() {
  const list = useListState<Creator>({ namespace: 'docs', inHash: false, defaults: { chip: 'all', sort: 'sales', dir: 'desc' }, fetcher: serve });
  return (
    <div>
      <ListToolbar
        search={{ value: list.query.q, onChange: (q) => list.set({ q }), placeholder: 'Search creators' }}
        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' }] }}
        reset={{ active: list.query.q !== '' || list.query.chip !== 'all', onReset: list.reset }}
        actions={<Button size="sm" onClick={list.retry}>Reload</Button>}
      />
      <DataTable
        label="Creators" columns={columns} rows={list.rows} rowKey={(c) => c.id} loading={list.loading} onClearFilters={list.reset}
        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={5} loading={list.loading} label="Creators" onPage={(page) => list.set({ page })} />}
      />
    </div>
  );
}

Sortable, filterable, paged list builds this into a full screen.

Save: useAction

useAction({ method, url }, options) returns run, pending, error (a sentence in the page's language), fieldErrors (keyed by field) and result. run(input) resolves to { ok: true, data } or { ok: false, kind, status, message, code, fieldErrors, error }. It never rejects on an HTTP failure. A second run while one is pending returns the same promise when the input is the same (a double click sends once); with another input nothing is sent and it resolves { ok: false, kind: 'busy' }. Messages come in English or Arabic (httpError), and the server's own words are used only for a 422 or a business refusal. codes maps a business code to your own message.

Save with field errors

run resolves to { ok: true, data } or { ok: false, … } and never rejects on an HTTP failure; a 422's field errors land in fieldErrors keyed by field, other failures in error in the language of the page. The pretend server wants 4 characters or more.

Code
import { useState } from 'react';
import { Button, DataProvider, FormField, createHttpClient, useAction } from '@ergasti/bricks';
import { demoServer } from './sample-data';

const client = createHttpClient({
  baseUrl: '/api',
  fetch: demoServer({
    'POST /api/codes': ({ body }) => {
      const code = String((body as { code?: string }).code ?? '');
      return code.length < 4 ? { status: 422, body: { message: 'Invalid.', errors: { code: ['Use at least 4 characters.'] } } } : { id: 1, code };
    },
  }, 600),
});

function Form() {
  const [code, setCode] = useState('KA');
  const [done, setDone] = useState('');
  const save = useAction<{ code: string }, { id: number; code: string }>({ method: 'POST', url: '/codes' }, { onDone: (data) => setDone(`Saved ${data.code}`) });
  return (
    <form onSubmit={(event) => { event.preventDefault(); setDone(''); void save.run({ code }); }} style={{ maxWidth: 320 }}>
      <FormField label="Coupon code" error={save.fieldErrors.code}><input value={code} onChange={(e) => setCode(e.target.value)} /></FormField>
      {save.error && <p role="alert">{save.error}</p>}
      <Button variant="rasp" disabled={save.pending} type="submit">{save.pending ? 'Saving…' : 'Save'}</Button>
      {done && <p>{done}</p>}
    </form>
  );
}

function Save() {
  return <DataProvider client={client}><Form /></DataProvider>;
}

An action can also be a function that gets the input and the client: useAction((id: number, client) => client.post(/codes/${id}/pause)).

Field errors in the blocks' forms

ChallengeRequestForm, SpecialCommissionForm and GroupForm take the server's 422 as fieldErrors (keyed by the server's field names) and the save's state as saving. Each error is drawn on its field with aria-invalid and described by it, focus moves once to the first invalid field, and a key the form cannot place is said above the buttons. The errors are applied when the save ends, so passing the same map again on a re-render does not bring back an error the user is fixing or move focus.

const save = useAction({ method: 'POST', url: `/groups/${group.id}/commission` });

<SpecialCommissionForm mode="set" members={group.member_count} saving={save.pending} fieldErrors={save.fieldErrors} error={save.error}
  onSubmit={(value) => save.run(value)} onCancel={close} />

A drawer with one loading state

Open a drawer with the row you already have and load only the body: useDrawerResource. See Details drawer with one loading state.

Debounce

useDebouncedCallback(fn, ms) and useDebouncedValue(value, ms) keep a keystroke from becoming a request. ListToolbar already waits for a pause in typing.

Language of the messages

DataProvider language is optional: without it the hooks speak the BricksProvider's language.

On this page