Search Docs

Search through documentation...

OpenStatus Logo

Examples

Each example is a block: one command installs a working route into your app, with every block it needs. The files are yours from then on. Change the columns, point the route at your data, or delete the folder when your own table is running.

BlockRouteData sourceLive modeChart
data-table-example-infinite/exampleIn-memory mock APINoYes
data-table-example-tinybird/example/logsTinybird datasourceYesYes

In-memory

npx shadcn@latest add @data-table-filters/data-table-example-infinite

This installs /example: a table schema, a mock API route that filters, computes facets and cursor-paginates in memory with the same semantics as the database handlers, and the infinite table with URL state, the command palette, the timeline chart and the row sheet. No database, no environment variables. Start the dev server and open /example.

Starting from an empty folder, the Quick Start creates the Next.js app and installs this example in one command.

When your rows live in a database, replace app/example/api/route.ts with a Drizzle or Tinybird handler. The client does not change.

Log viewer on Tinybird

npx shadcn@latest add @data-table-filters/data-table-example-tinybird

This installs /example/logs: the example table with live mode, the timeline chart, facets and the row sheet, on a route built with the Tinybird handler. It also installs the in-memory example at /example, whose schema and rows it shares.

Then, with the Tinybird CLI installed:

tb local start
(cd tinybird && tb deploy)
npx tsx app/example/logs/seed.ts --follow

The seed script appends 5,000 rows over the last week, then one new row a second until you stop it. That gives live mode something to follow. Start the dev server and open /example/logs.

Neither TINYBIRD_URL nor TINYBIRD_TOKEN is needed locally: the example defaults to Tinybird Local at http://localhost:7181 and reads its admin token from there. For Tinybird Cloud, set both, in your shell or in .env.local:

export TINYBIRD_URL=https://api.tinybird.co   # or your region's API host
export TINYBIRD_TOKEN=p.ey...                 # a token that can read the datasource

tb deploy deploys the tinybird folder as your local workspace's project. If you already have a Tinybird project, copy tinybird/datasources/logs.datasource into it instead.

What gets installed

FilePurpose
lib/tinybird/*The handler, the query client, the SQL literals
components/data-table/data-table-liveThe Live button and the marker row
hooks/use-live-mode.tsTracks when live mode was switched on
app/example/logs/api/route.tsThe route: createTinybirdHandler and timelineChart
app/example/logs/tinybird.tsURL, token, the query function, and the row → event mapping
app/example/logs/seed.tsAppends rows through the Events API
app/example/logs/client.tsxThe table with live mode
app/example/logs/page.tsxThe page: parses the URL state and renders the client
app/example/logs/schema.tsThe URL state: the example's filters plus live
app/example/logs/query-options.tsThe query options for /example/logs/api
tinybird/datasources/logs.datasourceThe datasource the route reads

To read your own datasource instead, change DATASOURCE in app/example/logs/tinybird.ts and columnMapping in app/example/logs/api/route.ts. If you keep the seed script, update toEvent to match. See Tinybird for every option.

Building one by hand

The examples are these four steps, filled in. Each step links to its guide page for details.

1. Define your table

Use createTableSchema to declare every column — display, filters, sorting, and row details — in one place. See Table Schema for the full API.

// table-schema.tsx
import {
  col,
  createTableSchema,
  type InferTableType,
} from "@/lib/table-schema";
 
export const tableSchema = createTableSchema({
  level: col.presets.logLevel(["error", "warn", "info", "debug"]),
  date: col.presets.timestamp().label("Date").size(200).sheet(),
  latency: col.presets
    .duration("ms")
    .label("Latency")
    .sortable()
    .size(110)
    .sheet(),
  status: col.presets.httpStatus().label("Status").size(60),
  method: col.presets.httpMethod(["GET", "POST", "DELETE"]).size(69),
  host: col.string().label("Host").size(125).sheet(),
});
 
export type ColumnSchema = InferTableType<typeof tableSchema.definition>;

2. Create the filter schema

Bridge the table schema to filter state with generateFilterSchema, then add non-column fields like sort and pagination. See State Management for details.

// schema.ts
import { createSchema, field } from "@/lib/store/schema";
import { generateFilterSchema } from "@/lib/table-schema";
 
export const filterSchema = createSchema({
  ...generateFilterSchema(tableSchema.definition).definition,
  sort: field.sort(),
  live: field.boolean().default(false),
  size: field.number().default(40),
});
 
export type FilterState = typeof filterSchema._type;

3. Set up the API route

Create an API handler with createDrizzleHandler that implements three-pass filtering, faceted search, and cursor pagination. See Drizzle ORM and Data Fetching for the underlying concepts.

// app/api/route.ts
import { createDrizzleHandler } from "@/lib/drizzle";
 
const handler = createDrizzleHandler({
  db,
  table: logs,
  schema: tableSchema.definition,
  columnMapping,
  cursorColumn: "date",
});
 
export async function GET(req: NextRequest) {
  const search = searchParamsCache.parse(
    Object.fromEntries(req.nextUrl.searchParams),
  );
  const result = await handler.execute(search);
  return Response.json(
    SuperJSON.stringify({
      data: result.data,
      meta: {
        totalRowCount: result.totalRowCount,
        filterRowCount: result.filterRowCount,
        facets: result.facets,
      },
      prevCursor: result.prevCursor,
      nextCursor: result.nextCursor,
    }),
  );
}

4. Render

Wire up useInfiniteQuery with DataTableInfinite and populate filter fields dynamically from server-side facet data. See Components for all available props.

// client.tsx
import { DataTableStoreProvider, useFilterState } from "@/lib/store";
import { useNuqsAdapter } from "@/lib/store/adapters/nuqs";
import {
  generateColumns,
  generateFilterFields,
  generateSheetFields,
} from "@/lib/table-schema";
import { useInfiniteQuery } from "@tanstack/react-query";
 
const columns = generateColumns<ColumnSchema>(tableSchema.definition);
const filterFields = generateFilterFields<ColumnSchema>(tableSchema.definition);
const sheetFields = generateSheetFields<ColumnSchema>(tableSchema.definition);
 
export function Client() {
  const adapter = useNuqsAdapter(filterSchema.definition, { id: "logs" });
 
  return (
    <DataTableStoreProvider adapter={adapter}>
      <DataTableContent />
    </DataTableStoreProvider>
  );
}
 
function DataTableContent() {
  const search = useFilterState<FilterState>();
  const { data, isFetching, fetchNextPage, hasNextPage } = useInfiniteQuery(
    dataOptions(search),
  );
 
  const flatData = React.useMemo(
    () => data?.pages?.flatMap((page) => page.data ?? []) ?? [],
    [data?.pages],
  );
 
  const { sort, live, size, ...filter } = search;
  const defaultColumnFilters = Object.entries(filter)
    .map(([key, value]) => ({ id: key, value }))
    .filter(
      ({ value }) => value != null && !(Array.isArray(value) && !value.length),
    );
 
  return (
    <DataTableInfinite
      columns={columns}
      data={flatData}
      defaultColumnFilters={defaultColumnFilters}
      defaultColumnSorting={sort ? [sort] : undefined}
      filterFields={filterFields}
      sheetFields={sheetFields}
      schema={filterSchema.definition}
      isFetching={isFetching}
      fetchNextPage={fetchNextPage}
      hasNextPage={hasNextPage}
      commandSlot={
        <DataTableFilterAICommand
          schema={filterSchema.definition}
          tableSchema={tableSchema.definition}
          api="/api/ai-filters"
          tableId="logs"
        />
      }
    />
  );
}

The commandSlot above uses the AI-enhanced command palette. It handles both structured queries (host:api) and natural language ("slow requests from eu") in the same input. See AI Filters for the full setup including the API route.

Live demos

These routes on this site run the setups above:

RoutePaginationData SourceLive ModeChart
/autoInfinite scrollIn-memoryNoNo
/defaultClient-sideIn-memoryNoNo
/infiniteInfinite scrollMock APIYesYes
/drizzleInfinite scrollPostgreSQLYesYes
/lightInfinite scrollTinybirdYesYes
/headlessInfinite scrollAny manifest endpointIf declaredIf declared