ProGridSign in

Examples

Live data and transactions

Patch individual rows through the grid handle instead of replacing the dataset. Built for feeds that never stop: updates batch, cells flash, and selection survives.

Live demo

Live data and transactions

Watch cells flash as rows change · Select a row and see it hold · Sort by a live column · Group while updates keep arriving

import { useEffect, useMemo, useRef, useState } from "react"
import { ProGrid, type ProColumnDef, type ProGridHandle } from "@/components/pro-grid"
import { formatCurrency, operationOrders, type OperationOrder } from "@/lib/operations-data"

function StatusCell({ value }: { value: unknown }) {
  const status = String(value)
  return <span className={`order-status order-status--${status.toLowerCase().replaceAll(" ", "-")}`}>{status}</span>
}

const baseColumns: ProColumnDef<OperationOrder>[] = [
  { accessorKey: "id", header: "Order", size: 118, meta: { label: "Order", type: "string" } },
  { accessorKey: "customer", header: "Customer", size: 190, meta: { label: "Customer", type: "string" } },
  {
    accessorKey: "region",
    header: "Region",
    size: 145,
    meta: {
      label: "Region",
      type: "string", filterVariant: "set",
      filterOptions: ["North America", "Europe", "Asia Pacific", "Latin America"],
      groupable: true,
      pivotable: true,
    },
  },
  {
    accessorKey: "status",
    header: "Status",
    size: 120,
    cell: ({ getValue }) => <StatusCell value={getValue()} />,
    meta: {
      label: "Status",
      type: "string", filterVariant: "set",
      filterOptions: ["On track", "At risk", "Delayed", "Complete"],
      groupable: true,
      pivotable: true,
    },
  },
  {
    accessorKey: "units",
    header: "Units",
    size: 88,
    meta: { label: "Units", type: "number", align: "right", aggregable: true, defaultAgg: "sum" },
  },
  {
    accessorKey: "revenue",
    header: "Revenue",
    size: 128,
    meta: {
      label: "Revenue",
      type: "number",
      align: "right",
      aggregable: true,
      defaultAgg: "sum",
      formatValue: (value) => formatCurrency(Number(value)),
    },
  },
]

/**
 * A stand-in for a bidding/trading feed: rows tick several times a second, new
 * orders arrive at the top and finished ones drop off the bottom — all through
 * `applyTransactionAsync` rather than by replacing `data`.
 */
const liveDemoSeed = operationOrders.slice(0, 40)

const LIVE_TICK_MS = 700

const LIVE_MAX_ROWS = 46

let liveSeq = 0

function nextLiveOrder(): OperationOrder {
  const template = operationOrders[(liveSeq * 17) % operationOrders.length]
  liveSeq += 1
  return {
    ...template,
    id: `ORD-9${String(liveSeq).padStart(4, "0")}`,
    status: "On track",
    units: 20 + Math.round(Math.random() * 380),
    revenue: 2000 + Math.round(Math.random() * 90000),
    margin: 10 + Math.round(Math.random() * 30),
  }
}

export function LiveDataDocsDemo() {
  const gridRef = useRef<ProGridHandle<OperationOrder>>(null)
  const [running, setRunning] = useState(true)
  const [commits, setCommits] = useState(0)

  // Held once and never replaced. The grid treats a new `data` array as
  // authoritative and discards applied transactions, so the seed rows have to
  // stay referentially stable and let the transactions do the moving.
  const [seed] = useState(() => liveDemoSeed)

  useEffect(() => {
    if (!running) return
    let ticks = 0

    const timer = setInterval(() => {
      const grid = gridRef.current
      if (!grid) return
      ticks += 1

      // Reading the live rows back is the point of `getRows` — the demo has no
      // copy of its own, the grid holds the truth.
      const rows = grid.getRows()
      const update: OperationOrder[] = []
      for (let i = 0; i < 6 && rows.length; i++) {
        const row = rows[Math.floor(Math.random() * rows.length)]
        if (update.some((r) => r.id === row.id)) continue
        const drift = 1 + (Math.random() - 0.5) * 0.08
        update.push({
          ...row,
          revenue: Math.round(row.revenue * drift),
          units: Math.max(1, Math.round(row.units * drift)),
          margin: Math.round((row.margin + (Math.random() - 0.5) * 3) * 10) / 10,
        })
      }

      // Every few ticks one order lands and the oldest completes, so adds and
      // removes get exercised alongside the updates.
      const churn = ticks % 5 === 0 && rows.length > 4
      grid.applyTransactionAsync({
        update,
        add: churn ? [nextLiveOrder()] : undefined,
        addIndex: 0,
        remove: churn ? [rows[rows.length - 1].id] : undefined,
      })
    }, LIVE_TICK_MS)

    return () => clearInterval(timer)
  }, [running])

  const live = useMemo(
    () => ({
      batchMillis: 80,
      flashMillis: 650,
      maxRows: LIVE_MAX_ROWS,
      onFlush: () => setCommits((n) => n + 1),
    }),
    [],
  )

  return (
    <>
      <div className="docs-demo__status" aria-live="off">
        <span>{running ? "Feed running — changed cells flash" : "Feed paused"}</span>
        <span>
          {commits} commit{commits === 1 ? "" : "s"} ·{" "}
          <button type="button" className="underline" onClick={() => setRunning((r) => !r)}>
            {running ? "Pause" : "Resume"}
          </button>
        </span>
      </div>
      <ProGrid<OperationOrder>
        ref={gridRef}
        columns={baseColumns}
        data={seed}
        getRowId={(row) => row.id}
        height={390}
        liveUpdates={live}
        title="Live order feed"
        toolbar={{ pivot: false, chart: false, refresh: false }}
      />
    </>
  )
}
Feed running — changed cells flash0 commits ·

Live order feed

Order
Customer
Region
Status
Units
Revenue
Total
Sum8580
Sum$1,742,820
40 rows

Things to try

  • Watch cells flash as rows change
  • Select a row and see it hold
  • Sort by a live column
  • Group while updates keep arriving

The Code tab above is the component rendering this page; the Data tab is what reaches the grid. The props behind it are explained in Live data and transactions.

Use ProGrid in your project