gridcn2.0.0
Server path

Go live with streaming

Step 5 of 5

Push live values from a WebSocket into the grid by row id with updateCells, without a refetch and without sending the push back to your server.

Before you start, handle failures. Your server can push new values while the user watches the grid. updateCells writes them into the rows that the grid holds. It needs no refetch.

Write pushed values

  1. Keep a ref to the grid. A socket handler runs after the grid mounted, so it reaches the actions through the ref.
  2. Open the socket in an effect. Close it in the cleanup.
  3. Map each message to patches. A patch names a row by its row id, and a column by its column id.
  4. Call actions.updateCells once for each message.

This grid applies price pushes to the rows it loaded:

"use client";

import { useEffect, useRef } from "react";
import {
  DataGrid,
  defineColumns,
  type DataGridApi,
} from "@/components/data-grid/data-grid";
import {
  DataGridPaginationBar,
} from "@/components/data-grid-pagination/data-grid-pagination";
import {
  useDataGridServerRows,
} from "@/components/data-grid-server/data-grid-server";

type Quote = { symbol: string; price: number };
type PriceMessage = Quote[];

const columns = defineColumns<Quote>()([
  { id: "symbol", header: "Symbol", accessorKey: "symbol" },
  { id: "price", header: "Price", accessorKey: "price", type: "number" },
]);

export function QuotesGrid() {
  const gridRef = useRef<DataGridApi<Quote>>(null);
  const server = useDataGridServerRows<Quote>({
    getRowId: (row) => row.symbol,
    fetchRows: async ({ spec, page, pageSize, signal }) => {
      const response = await fetch("/api/quotes/query", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ spec, page, pageSize }),
        signal,
      });
      const answer = await response.json();
      return { rows: answer.rows, totalRowCount: answer.total };
    },
  });

  useEffect(() => {
    const socket = new WebSocket("wss://example.com/prices");
    socket.onmessage = (event) => {
      const message: PriceMessage = JSON.parse(event.data);
      gridRef.current?.actions.updateCells(
        message.map(({ symbol, price }) => ({
          rowId: symbol,
          columnId: "price",
          value: price,
        })),
        { source: "stream" },
      );
    };
    return () => socket.close();
  }, []);

  return (
    <>
      <DataGrid
        ref={gridRef}
        {...server.gridProps}
        columns={columns}
        className="h-96"
      />
      <DataGridPaginationBar {...server.pager} />
    </>
  );
}

One call is one batch. The grid applies all patches together and calls onDataChange once. Rows without a patch do not render again.

What the grid skips

updateCells returns a verdict. applied counts the cells it wrote. skipped lists a patch that the grid checked and left out, with a reason. A patch for a row that the grid has not loaded gets the reason "unknown-row". A push to a row whose save is in flight gets "saving": the grid holds it and applies it once the save settles. A call with more than 100,000 patches skips the extra patches with "limit".

With async validation, pending is true and the verdict reports no outcome. See Read the push verdict for every reason.

A push with source: "stream" writes into a readOnly grid. A push without source is refused there. A push skips a column that has no write path (an accessorFn without setValue) with the reason "readonly". A call with another source, such as { source: "edit" }, skips every patch for a read-only grid, column, or row with "readonly".

A batch has the source "stream". onSave never receives that source, so a pushed value does not go back to your server. Pass { source: "edit" } to a call to send it to onSave.

The grid does not sort server rows, so a pushed value never moves its row. Your next fetch returns the server order. If the push changes a column that your server sorts or filters by, the row turns stale. See Push into a server-ordered view.

Result

When the socket sends a price, the cell in that row changes. The row keeps its position and the selection stays. A push sends no request. A push into a column that your server sorts or filters by leaves the row in place and stale. The hook reshapes the view one second later. Call server.reshape() to reshape at once.

Where next: the custom code path, the task finder, or Stream updates for undo of pushed values.

On this page