DataHooks
usePaged
A paged list over useResource: rows, total, lastPage and summary read from the envelope, the page sent as page=. When the last page empties (its last row was removed) it steps back to the new last page. An answer that is not a page (adapter returns null) is an error with the answer's status (200).
import { usePaged } from '@ergasti/bricks';Examples
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>;
}Signature
function usePaged<T, S>(url: string | null, options?: PagedOptions<T, S>): PagedResult<T, S>Parameters
Prop
Type
Returns
PagedResult<T, S>
Related
useResource · DataProvider · useAction · useDataLanguage · useDebouncedCallback · useDrawerResource
Source
src/data/usePaged.ts (line 84) on GitHub.