# Tables

A paginated table you control: it asks for a page and you fetch it.

The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).

`TablePaginated` holds no data of its own. It reports the page, the [page size](/docs/tables.md#page-size) and the sort. You fetch that slice and pass it back, so one page is in memory at a time.

## A paginated table

Here a local array stands in for the server. Sort a column or change page, and the table asks for the new slice.

```tsx title="CustomersTable.tsx"
import { useState } from 'react';
import { TablePaginated, dimension, measure, results } from 'em-kit';
import type { TablePaginatedProps } from 'em-kit';

type TableState = NonNullable<TablePaginatedProps['state']>;
type Customer = { customer: string; orders: number; revenue: number };

const customer = dimension({ name: 'customer', title: 'Customer' });
const orders = measure({ name: 'orders', title: 'Orders' });
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', decimalPlaces: 0 },
});

export function CustomersTable() {
  const [state, setState] = useState<TableState>({ page: 0, isLoadingDownloadData: false });

  // The table reports the page, the page size that fits its height, and the sort.
  const { rows, total } = fetchCustomers(state);

  return (
    <div style={{ height: 420 }}>
      <TablePaginated
        title="Customers"
        dimensionsAndMeasures={[customer, orders, revenue]}
        results={results(rows)}
        totalResults={{ isLoading: false, total }}
        allResults={results(customers)} // every row, for the export menu
        state={state}
        setState={setState}
      />
    </div>
  );
}

// Stand-in for your API: sort, then return one page and the total row count.
const names = [
  'Alder & Finch', 'Brightwater', 'Cobalt Freight', 'Dunmore Labs', 'Eastgate Foods',
  'Fernhill', 'Granite Works', 'Harbour Lane', 'Ironbridge', 'Juniper Health',
  'Kestrel Air', 'Larkspur Media', 'Marlow & Reed', 'Northgate', 'Oakfield Dairy',
  'Pinecrest', 'Quayside Books', 'Redwater', 'Saltmarsh', 'Thornbury',
  'Umber Clay', 'Vale Cycles', 'Westbrook', 'Yarrow Tea',
];
const customers: Customer[] = names.map((customer, i) => ({
  customer,
  orders: 12 + ((i * i * 29) % 61),
  revenue: 1800 + ((i * i * 7919) % 42000),
}));

function fetchCustomers({ page, pageSize = 10, sort }: TableState) {
  const sorted = [...customers];
  if (sort) {
    const key = sort.id as keyof Customer;
    const sign = sort.direction === 'desc' ? -1 : 1;
    sorted.sort((a, b) => (a[key] > b[key] ? sign : a[key] < b[key] ? -sign : 0));
  }
  return {
    rows: sorted.slice(page * pageSize, (page + 1) * pageSize),
    total: customers.length,
  };
}
```

Result: a table of five rows with sortable column headers and “Page 1 of 5” under it.

## What you pass

| Prop | What it is |
|---|---|
| `state`, `setState` | The table’s state, kept by you: `page`, `pageSize`, `sort` and `isLoadingDownloadData`. |
| `results` | The rows of the current page. |
| `totalResults` | `{ isLoading, total }`: the total row count, which sets the number of pages. |
| `allResults` | Every row, for the CSV and Excel export. `state.isLoadingDownloadData` turns `true` when a reader asks for one, so you can fetch them only then. |

## Page size

Left alone, the table shows as many rows as fit its height, so it fills a card of any size and follows it when the card is resized. For a fixed number, pass `pageSize`, for example `pageSize={5}`. Either way the table reports it in `state.pageSize`, so slice your rows by that.

Give a card with a `pageSize` room for its rows: about 40 pixels each, on top of the header row, the pager and the card’s title. Rows that do not fit scroll inside the card.

`setState` can be any function that stores the new state, not only the setter from `useState`.

## Other tables

The [scrollable table](/docs/components/table-scrollable.md) loads more rows as the reader scrolls. The [pivot table](/docs/components/pivot-table.md) and the [heat map](/docs/components/heat-map.md) take the same fields and the same `results`.
