useResource
One GET resource. Race-safe: a url/params change, a new client or an unmount aborts the request in flight, and an answer for anything but the latest request is ignored. url === null (or enabled: false) is idle. Params are keyed by resourceUrl, so a new object with the same values does not refetch.
import { useResource } from '@ergasti/bricks';Examples
Load with params
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>
);
}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>;
}Wait for what you need
url: null (or enabled: false) keeps the hook idle until you have it.
Code
import { useState } from 'react';
import { Button, useResource } from '@ergasti/bricks';
function Idle() {
const [id, setId] = useState<number | null>(null);
const one = useResource<{ name: string }>(id === null ? null : `/creators/${id}`);
return <div><Button onClick={() => setId(7)}>Pick a creator</Button> <small>status: {one.status}</small></div>;
}Signature
function useResource<T>(url: string | null, options2?: ResourceOptions): UseResourceResult<T>Parameters
options2: ResourceOptions
Prop
Type
Returns
UseResourceResult<T>
Related
useHttpClient · DataProvider · Button · useAction · useDataLanguage · useDebouncedCallback · useDrawerResource
Source
src/data/useResource.ts (line 71) on GitHub.