SpreadsheetGrid
Guides

Server-side row model (SSRM)

Block fetching, query forwarding and write-back (optimistic updates + rollback) with dataSource

Pass dataSource instead of rows to use the server-side row model (SSRM). It keeps the vertical scroll space for the total number of rows, and fetches only the blocks near the visible area with getRows (unloaded rows show as skeletons). Filters, sorting and the global filter are executed by the server.

Demo (50,000 rows fetched from a server)

This demo actually calls a Next.js Route Handler (/api/ssrm). You can watch the blocks being fetched in the Network tab of the developer tools.

Rows 50000 of 50000Columns 8 of 8Sort: —
#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Rows 50000 of 50000Columns 8 of 8
Cell —Range —0 cells / 0 rows0 columns

Event notifications show up here

Try:

  • Scrolling — only blocks in the visible area are fetched one after another (blockSize: 100). A band of light (shimmer) flows over skeletons while fetching, and arriving rows fade in from top to bottom (a 1500ms latency makes it easier to see).
  • Filters / sorting — the query is forwarded to the server, and the result set is replaced entirely (with a debounce of about 300ms).
  • Set "While refetching" to "Dim the previous rows" and filter / sort / reload — until the new rows arrive, the previous rows are shown dimmed, and a line flows below the column headers (serverSideRefetch="keep"; a 1500ms latency makes it easier to see).
  • "Make fetching fail" + scrolling or reloading — the built-in error bar (with retry) appears. Uncheck it and press "Retry" to recover.
  • Editing cells (Status / Qty / Unit price) — write-back with updateRows. It's an optimistic update, so the screen reflects it immediately. While saving, the cell shows stripes and a spinner, and ✓ on success (showSaveStatus; uncheck it to hide the marks).
  • "Make saving fail" + editing a cell — the value is rolled back automatically, and the save failure bar appears.
  • Note: the demo server is stateless, so edited values aren't saved (refetching restores them).

A sample running the same shape with a fake server in the browser opens on StackBlitz (100,000 rows; getRows / updateRows, and an example of interpreting query on the server side).

Minimal implementation

import {
  SpreadsheetGrid,
  type ServerSideDataSource,
} from '@ishibashi0112/spreadsheet-grid'

const dataSource: ServerSideDataSource<Row> = {
  getRows: async ({ startIndex, endIndex, query, signal }) => {
    const res = await fetch('/api/rows', {
      method: 'POST',
      body: JSON.stringify({ startIndex, endIndex, query }),
      signal,
    })
    // return { rows: Row[], totalRowCount: number }
    return res.json()
  },
  // optional: enables cell editing (optimistic update + rollback on failure)
  updateRows: async ({ updates }) => {
    await api.patchRows(updates)
  },
  initialRowCount: 50_000, // optional: reserve the total height before the first fetch
  blockSize: 100,          // default 100
}

<SpreadsheetGrid
  dataSource={dataSource}
  columns={columns}
  rowKeyGetter={(row) => row.id} // stable keys required for write-back
/>

The getRows contract

  • params is { startIndex, endIndex, query, signal }. Return only the range [startIndex, endIndex) passed in (returning every row is the same as holding every row on the client, and SSRM loses its point).
  • Return the total count after filtering with query applied as totalRowCount (the vertical scroll space follows).
  • When signal is aborted, reject promptly (it happens when scrolling past, on query changes and on unmount; it isn't treated as a failure).

Query forwarding (ServerSideQuery)

query is { globalText?, columnFilters?, sort? }. columnFilters arrive as descriptors with a kind (text / number / date / select / set / custom) as is, so convert them to a WHERE clause on the server. For an implementation example, see this demo's source.

  • The client supplies the options for set / select filters (it doesn't hold every row, so it can't collect them automatically). For low-cardinality columns, give filterOptions statically; for columns whose options come from the server, use the grid prop getFilterOptions (returns options asynchronously every time the popover opens; see Sorting and filtering); for high-cardinality columns, use text / number filters. Without '' in the options, no "(Blank)" item appears, and with forms that send only the chosen values (unchecking values in columns with filterOptions and so on), blank rows disappear too, so for columns with blank rows, include { value: '', label: '(Blank)' } in the options.
  • To block sorting / filtering, set enableSorting / enableColumnFilter / enableGlobalFilter to false.

Relative dates and time zones

The date column filter's "Today", "This month" and "Last 30 days" (relative presets) arrive still relative, like { mode: 'preset', preset: 'today' }. If the server decides the range, "Today" becomes today in the server's time zone (when a user in Tokyo opens it between 0:00 and 9:00, it's still the previous day on a UTC server). To filter by the user's today, read the user's time zone in getRows, which is called in the browser, and add it to the request; the server then decides the range with that date.

const dataSource: ServerSideDataSource<Row> = {
  async getRows({ startIndex, endIndex, query, signal }) {
    const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; // e.g. 'Asia/Tokyo'
    const res = await fetch('/api/rows', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ startIndex, endIndex, query, timeZone }),
      signal,
    });
    return res.json();
  },
};

When the date changes while the grid stays open, blocks are refetched on days the range changes ("Today" every day, "This month" at the start of the month) (the query sent is the same, so the server resolves it again with that day's date).

Write-back (updateRows) and optimistic updates

  • Edits are reflected on screen immediately (optimistic values) and confirmed when updateRows resolves. On reject, they're rolled back automatically to the values before the edit, and the save failure bar is shown.
  • updates are per-row descriptors ({ rowKey, rowIndex, row, previousRow, changes }), and multi-row edits from paste are combined into one call.
  • If the server normalizes values, return { rows } and they're merged into the cache.
  • Return stable keys from rowKeyGetter (database primary keys and so on) (the default is the view index, which isn't suited to write-back).

Refreshing and error handling

  • refreshServerSide() (imperative handle) — refetches the latest from the server without changing the query, keeping the scroll position. Use it to reflect additions, removals and edits made outside (for a declarative form, the serverSideRefreshToken prop).
  • Fetch failures — failed blocks stay as skeletons, and the built-in error bar (retry / close) appears. You can also get outside notifications (toasts and so on) with onServerSideLoadError.
  • Save failures — automatic rollback + the save failure bar. You can build your own retry path from params.updates of onServerSideWriteError (it holds only the cells that were restored; changes already overwritten by later edits to the same cells aren't included).
  • Refreshing while saving — refreshing, or changing filters / sorting while saving, waits for the save to settle (up to 3 seconds) before refetching. The latest edit is never shown with an old value (a save that succeeds after 3 seconds keeps the rows on screen and refetches the visible range once more, for the new values).

How refetching looks (serverSideRefetch)

When filters / sorting change and on reload (refreshServerSide() / serverSideRefreshToken), rows become loading rows (skeletons) by default. With serverSideRefetch="keep", the previous rows stay visible, dimmed, until the new rows arrive, and a line flowing left to right appears below the column headers (since 1.5.0).

<SpreadsheetGrid
  dataSource={dataSource}
  columns={columns}
  rowKeyGetter={(row) => row.id}
  serverSideRefetch="keep"
/>
  • Once all new rows of the visible range arrive, they replace the old ones at once. Arriving blocks aren't mixed in one by one (to avoid showing a table with the new order on top and the old order below). If fetching that range fails, the previous rows give way to loading rows and the error bar.
  • While previous rows are shown, editing, paste, deletion and the fill handle don't run (the positions of the previous rows don't match the new result). The table (role="grid") gets aria-busy="true".
  • The look can be changed with tokens: --ssg-refetch-row-opacity (strength of previous rows; default 0.45) / --ssg-refetch-bar (line color; default the accent color) / --ssg-refetch-bar-track (the line's track). With motion="off", the line stops.
  • On the first fetch, and when nothing has arrived yet, rows are loading rows even with "keep".

Limitations

  • Row grouping (rowGroup), undo/redo and automatic row / column growth on paste don't work with serverSide.
  • There's no write-back API for adding or removing rows, so go with "apply on the server → refreshServerSide()".
  • To switch between clientSide ↔ serverSide at runtime, change key to remount.

On this page