Skip to Content
BBRICKSv0.7.4
DataOverview

HTTP client

createHttpClient, HttpError and the helpers that read errors.

Data hooks do not call fetch themselves. They use an HttpClient: one per app, made with createHttpClient and handed down by DataProvider, or passed to any hook as its client option. With neither, hooks use a default same-origin client that reads the CSRF token from <meta name="csrf-token">.

const client = createHttpClient({
  baseUrl: '/en/merchant/affiliate-brand-console/api',
  onUnauthorized: () => window.location.assign('/login'), // 401 and 419
});

<DataProvider client={client} language={language}>
  <App />
</DataProvider>;

await client.post('/codes', { code: 'KARI' }); // parsed JSON, or throws HttpError

get, post, put, patch, delete and upload (multipart) all take { params, headers, signal }. Requests are JSON in and out, send X-Requested-With: XMLHttpRequest (so a Laravel backend answers JSON) and the CSRF token, use same-origin cookies by default, and accept an injected fetch for tests and for the pretend servers these docs use.

Errors

A failed request throws an HttpError: status (0 means the network failed), message (the server's own words for a 422 or a business refusal, otherwise ''), errors (field errors from a 422), code (a business code the server sent) and data (the parsed body). Late replies to aborted requests are never an error to show: isAbortError tells them apart.

createHttpClient

function

A JSON client for Laravel-style APIs: same-origin cookies, JSON in and out, X-Requested-With (so Laravel answers errors as JSON) and, for a write, the CSRF token. The CSRF token, X-Requested-With and the shared headers go only to trusted origins (the page's, baseUrl's, trustedOrigins), never to another origin's absolute URL. A 2xx resolves to the parsed body (null when empty); a 2xx body that is not JSON throws an HttpError with code: 'not_json'; anything else throws an HttpError (status 0 for the network). An abort rejects with the AbortError itself. No global state: make one per app and hand it to DataProvider (or to each hook's client).

function createHttpClient(options?: HttpClientOptions): HttpClient

Prop

Type

Source: src/data/http.ts (line 205)

HttpError

class

A failed request. status 0 = the network (no answer). message is the server's own words only where they are meant for the viewer (a 422 or a business refusal, see serverMessage); otherwise '' and the UI shows httpError copy. errors is the 422 field bag, code the business code (error or code in the body), data the parsed body.

class HttpError

Source: src/data/http.ts (line 17)

toHttpError

function

An answer's status and body → the HttpError the client throws for it.

function toHttpError(status: number, data: unknown): HttpError

Prop

Type

Source: src/data/http.ts (line 113)

isAbortError

function

True for a fetch the caller (or a newer request) aborted: never an error to show.

function isAbortError(reason: unknown): boolean

Prop

Type

Source: src/data/http.ts (line 120)

serverMessage

function

The server's own words, only where they are meant for the viewer: a 422 or a business refusal (409 overlap, 423 busy, …). Laravel's English for a session, permission, rate-limit, CSRF, missing route or server failure ("Unauthenticated.", "This action is unauthorized.") gives way to the localized copy (httpError) → ''.

function serverMessage(status: number, data: unknown): string

Prop

Type

Source: src/data/http.ts (line 92)

errorBagOf

function

The 422 bag, only when it has the Laravel shape; a bare string per field is wrapped.

function errorBagOf(data: unknown): ErrorBag | undefined

Prop

Type

Source: src/data/http.ts (line 98)

fieldErrorsOf

function

{ field: [message, …] } → { field: first message } (what a form shows under each field).

function fieldErrorsOf(source: HttpError | ErrorBag | Record<string, unknown> | null | undefined): Record<string, string>

Prop

Type

Source: src/data/http.ts (line 105)

errorInfo

function

Anything thrown by a request → { status, message } (status 0 when it is not an HttpError).

function errorInfo(reason: unknown): HttpError

Prop

Type

Source: src/data/http.ts (line 125)

metaCsrfToken

function

The Laravel layout's <meta name="csrf-token">, or null (no document: SSR, tests).

function metaCsrfToken(): string | null

Source: src/data/http.ts (line 132)

Building a URL

resourceUrl(path, params) is what hooks use to put params on a URL. Keys are sorted, empty values (undefined, null, '', []) are skipped, and arrays become repeated key[]:

resourceUrl('/api/x', { q: 'sara', page: 2, tier: '', ids: [1, 2] }); // '/api/x?ids[]=1&ids[]=2&page=2&q=sara' (encoded)

resourceUrl

function

The request URL: params appended in key order (so {a, b} and {b, a} are the same URL, and the same resource key), empty values (undefined, null, '', []) skipped, arrays as repeated key[]. Joins onto an existing ?query.

function resourceUrl(base: string, params?: Params): string

Prop

Type

Source: src/data/http.ts (line 147)

Fetchers for lists

listFetcher(client, url, options) adapts a client and an endpoint to the fetcher useListState wants: it maps a ListQuery (search, chip, selects, sort, page) to request params and the response to a ListPage.

listFetcher

function

useListState's fetcher, over an HttpClient: useListState({ namespace, fetcher: listFetcher(client, url) }). The sort and dir are sent only when a sort is set (the dir sent is the dir shown). Errors are the client's HttpError, which carries the status useListState reads. Build it once (useMemo) per client and url.

function listFetcher<T>(client: HttpClient, url: string, options3?: ListFetcherOptions<T>): (query: ListQuery, signal: AbortSignal) => Promise<ListPage<T>>

options3: ListFetcherOptions<T>

Prop

Type

Source: src/data/listFetcher.ts (line 20)

pageAdapters

constant

Ready-made envelopes. auto (the default) tries pagination, then meta, then a bare Laravel paginator, then a plain array.

const pageAdapters: { pagination: <T, S = unknown>(body: unknown) => PageInfo<T, S> | null; meta: <T, S = unknown>(body: unknown) => PageInfo<T, S> | null; paginator: <T, S = unknown>(body: unknown) => PageInfo<T, S> | null; array: <T, S = unknown>(body: unknown) => PageInfo<T, S> | null; auto: <T, S = unknown>(body: unknown) => PageInfo<T, S> | null; }

Source: src/data/usePaged.ts (line 35)

failureOf

function

A failed request → what the UI says. The server's own words for a 422 or a business refusal (409, 423, …; see serverMessage), a codes entry for a known business code, else the house copy from httpError (EN/AR): Laravel's English for a session, permission, CSRF, rate limit or server error never reaches the viewer.

function failureOf(reason: unknown, language: Lang, codes?: CodeMessages): { ok: false; status: number; kind: ActionFailure; message: string; code?: string; fieldErrors: Record<string, string>; error: HttpError; }

Prop

Type

Source: src/data/useAction.ts (line 35)

toDataError

function

A thrown request error → the state's error: status, the viewer-facing message, code and bag when present.

function toDataError(reason: unknown): DataError

Prop

Type

Source: src/data/useResource.ts (line 34)

Test seams

fakeFetch.ts (fakeServer, deferredFetch) is for the library's own tests: it is not exported, not built and not in the package. The examples in these docs use a small pretend server of their own (docs/examples/_sample.ts), built on the fetch option.

On this page