Data table
A table of products. Click a column header to sort, type to search, change the page size or move between pages. The server does the work; the table sends its state as query params and keeps the old rows, dimmed, until the new ones arrive.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { createClient } from "@hyper-fetch/core";
export const client = createClient({ url: "https://dummyjson.com" });
export type Product = { id: number; title: string; category: string; price: number; rating: number; stock: number };
export type SortKey = "title" | "category" | "price" | "rating" | "stock";
export type Order = "asc" | "desc";
/** The server sorts, filters and pages. The table only sends the state of its controls as typed query params. */
export const searchProductsRequest = client.createRequest<{
response: { products: Product[]; total: number; skip: number; limit: number };
queryParams: { q: string; sortBy: SortKey; order: Order; limit: number; skip: number; select: string };
}>()({ endpoint: "/products/search" });
npx tiged BetterTyped/hyper-fetch/examples/react/data-table hyper-fetch-react-data-table && cd hyper-fetch-react-data-table && npm install && npm run dev- Server-side table state:
sortBy,order,q,limitandskipare typed query params of one request. keepPreviousData: "preserve"keeps the current rows on screen while the next sort or page loads.bouncewaits until you stop typing before the search request is sent.- Accessible sorting with
aria-sorton the sorted column header.
How it works
-
api.tstypes the query params of/products/search.sortByonly accepts the column keys, so the headers and the request cannot drift apart. -
App.tsxkeeps the table state inuseStateand builds the request from it on every render. Each combination has its own cache key, so a page you already saw is shown at once. -
The hook options:
useFetch(searchProductsRequest.setQueryParams({ ... }), {keepPreviousData: "preserve",bounce: true,bounceTime: 300,});"preserve"keepsdatafrom the previous request until the new response arrives. The default,"auto", does the same when only query params change;"preserve"states it and also covers changes of endpoint params. Whileloadingistrueand old data is shown, the rows are dimmed. -
bounce: truedebounces changes of the request. Typing "lap" sends one request forq=lap, not three. The first request on mount is not delayed. -
Sorting by a new column starts in ascending order, clicking the same column again flips it. Changing the search, sort or page size goes back to the first page.
- Admin tables, reports and catalogs that are too large to load at once.
- If you need to share or bookmark the table state, keep it in the URL instead. See the URL filters example.
Related
The table sends its sort, search and page as typed query params. keepPreviousData keeps the rows steady between
requests and bounce keeps typing from flooding the server.
