Your users type a question, and your table filters, sorts, groups or selects its top rows. You add one route to your server and one hook to your table. Gridsay's plugin is compatible with TanStack Table, tested with version 9.3.1. TanStack Table is MIT-licensed open source by its own maintainers; the plugin is MIT licensed too.
The plugin's API may change before 1.0. Before 1.0, a breaking change raises the minor version.
Orders over 500 from Germany, newest first
filter Total is greater than 500filter Country is Germanysort Placed, newest firstonly the ones over 1000
filter Total is greater than 1000filter Country is Germanysort Placed, newest firstThe second question follows the first: it keeps the country and the order, and replaces the amount.
@tanstack/react-table v9, 9.3.1 or later. Version 8 is not supported, and neither are tables built on it, such as Material React Table and Mantine React Table.fast is the default and suits most tables.Put both in your server's environment:
# Save at your app root, beside package.json. Restart your dev server after saving.GRIDSAY_URL=<your Gridsay URL, from the dashboard>GRIDSAY_SECRET_KEY=<your secret key>Keep the secret key on your server. Anyone who has it can spend your credits. To call Gridsay from the browser instead, read Browser keys.
The route adds your secret key, forwards the table's request to Gridsay, and returns the response and its status unchanged. It never follows a redirect.
// If your app uses src/, create src/app/api/tanstack-table/route.ts instead. export async function POST(request: Request) { // Each question spends your credits, so only your signed-in users may ask. if (!(await isSignedIn(request))) { return Response.json({ ok: false, code: 'unauthenticated_user', message: 'Sign in to use the assistant.' }, { status: 401 }); } const key = process.env.GRIDSAY_SECRET_KEY; const gateway = process.env.GRIDSAY_URL; if (!key || !gateway) { console.error('[Gridsay] Set GRIDSAY_SECRET_KEY and GRIDSAY_URL in .env.local at your app root. Restart your dev server.'); return Response.json({ ok: false, message: 'The assistant is not configured. Please contact the app owner.' }, { status: 500 }); } const body = await request.text(); let response: Response; try { response = await fetch(`${gateway}/api/v1/datagrid/prompt`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-api-key': key, origin: request.headers.get('origin') ?? '', }, body, // Never follow a redirect: it would send your key to another address. redirect: 'error', }); } catch { console.error('[Gridsay] Could not reach the gateway. Check GRIDSAY_URL and your server’s network connection.'); return Response.json({ ok: false, message: 'The assistant cannot connect right now. Try again later.' }, { status: 503 }); } if (!response.ok) console.error('[Gridsay] Request failed:', response.status, await response.clone().text()); const headers = new Headers({ 'content-type': 'application/json' }); const retryAfter = response.headers.get('Retry-After'); if (retryAfter !== null) headers.set('Retry-After', retryAfter); return new Response(response.body, { status: response.status, headers });} async function isSignedIn(request: Request) { // Your sign-in check goes here, e.g. return Boolean(await getSignedInUser(request)); if (process.env.NODE_ENV === 'development') return true; console.error('[Gridsay] Refused: add your sign-in check to isSignedIn before you deploy.'); return false;}Before you deploy, put your own sign-in check in isSignedIn. As written, the route answers only on your dev server. A caller it turns away gets status 401, code unauthenticated_user and "Sign in to use the assistant."
Install the plugin, with TanStack Table v9:
npm install @gridsay/tanstack-table @tanstack/react-table@^9.3.1Then add three things to your table: the features the assistant may change, assistantColumn as the default column, and the useTableAssistant hook. The question box is yours; this one is a form with a text box.
'use client'; import { assistantColumn, assistantGroupedRowModel, useTableAssistant,} from '@gridsay/tanstack-table/react';import { columnFilteringFeature, columnGroupingFeature, createColumnHelper, createExpandedRowModel, createFilteredRowModel, createSortedRowModel, rowExpandingFeature, rowSelectionFeature, rowSortingFeature, tableFeatures, useTable,} from '@tanstack/react-table';import { useState } from 'react'; // The assistant changes only what you register here.const features = tableFeatures({ columnFilteringFeature, filteredRowModel: createFilteredRowModel(), rowSortingFeature, sortedRowModel: createSortedRowModel(), columnGroupingFeature, groupedRowModel: assistantGroupedRowModel(), // in place of createGroupedRowModel() rowExpandingFeature, expandedRowModel: createExpandedRowModel(), rowSelectionFeature,}); type Order = { customer: string; country: string; status: string; total: number; placedAt: Date }; const columnHelper = createColumnHelper<typeof features, Order>();const columns = columnHelper.columns([ columnHelper.accessor('customer', { header: 'Customer' }), columnHelper.accessor('country', { header: 'Country' }), columnHelper.accessor('status', { header: 'Status', meta: { assistant: { type: 'singleSelect', options: ['open', 'paid', 'refunded'] } }, }), columnHelper.accessor('total', { header: 'Total', meta: { assistant: { description: 'Order total in euros' } }, }), columnHelper.accessor('placedAt', { header: 'Placed' }),]); export function Orders({ data }: { data: Order[] }) { const table = useTable({ features, columns, data, defaultColumn: assistantColumn, // the line that lets the assistant filter and sort initialState: { expanded: true }, // groups the assistant makes show their rows... autoResetExpanded: false, // ...and stay open after the next answer }); const { ask, undo, canUndo, pending, error } = useTableAssistant(table, { url: '/api/tanstack-table' }); const [question, setQuestion] = useState(''); return ( <> <form onSubmit={async (event) => { event.preventDefault(); if (await ask(question)) setQuestion(''); }} > <input aria-label="Ask about the orders" value={question} onChange={(event) => setQuestion(event.target.value)} readOnly={pending} placeholder="Orders over 500 from Germany, newest first" /> <button type="submit" disabled={pending || !question.trim()}> Ask </button> <button type="button" disabled={pending || !canUndo} onClick={() => undo()}> Undo </button> </form> {error ? <p role="alert">{error.message}</p> : null} <table> <thead> {table.getHeaderGroups().map((headerGroup) => ( <tr key={headerGroup.id}> {headerGroup.headers.map((header) => ( <th key={header.id}> <table.FlexRender header={header} /> </th> ))} </tr> ))} </thead> <tbody> {table.getRowModel().rows.map((row) => row.getIsGrouped() ? ( <tr key={row.id}> <th colSpan={columns.length}> {String(row.groupingValue)} ({row.getLeafRows().length}) </th> </tr> ) : ( <tr key={row.id} className={row.getIsSelected() ? 'selected' : undefined}> {row.getAllCells().map((cell) => ( <td key={cell.id}> <table.FlexRender cell={cell} /> </td> ))} </tr> ), )} </tbody> </table> </> );}Render <Orders data={orders} /> from your page with your own orders. Keep total a number and placedAt a date, and format them when you render cells.
assistantColumn puts the plugin's filter and sort functions on each column. See Describing columns for types, descriptions and option lists.assistantGroupedRowModel() lets the assistant group. With TanStack's own grouped row model, it does not group. See Grouping.Type Orders over 500 from Germany, newest first. The table filters and sorts, and ask resolves true. Then ask a follow-up, such as only the ones over 1000: the conversation and the table's current view go with the next question.
ask resolves true once the answer is on the table. When the assistant cannot answer, it resolves false, the table stays as it was, and error.message is a sentence to show your user.Now ask make a chart of orders by country. TanStack Table has no chart, so the assistant declines: ask resolves false and error has status 422 and code query_not_understood. A declined question is charged, like an answer. Read Refusals and errors before you add retries.
Both questions appear under Requests on the dashboard's Usage page.
The reference and the guides that were on this page now have pages of their own.
Options: Options for both APIs.
Reading GridsayError: GridsayError's fields.
reset(): Undo and reset.
Follow-ups and undo: Undo and reset.
Describe your columns: Describing columns.
Controlled state: Controlled state.
Sorting and grouping on your server: Server-side data.
The size ceiling: Limits.
Limits: Limits.
Troubleshooting: Refusals and errors.
What is charged: What is charged.