# Streaming live updates

> Apply a stream of WebSocket messages to the grid with batched applyTransaction calls, flash changed cells and keep sorting and selection stable.

Prices, stock levels and job statuses change many times a second. Calling `setRows()` for each message rebuilds the whole model; `applyTransaction()` touches only the rows that changed. This recipe batches messages per animation frame and highlights what changed.

**Live demo: Streaming updates** (runs on the HTML version of this page). Source of `demos/recipe-grid-live-updates.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { button, docsTheme, layout, onDocsThemeChange, seededRandom } from './_shared';

export const meta = { title: 'Streaming updates', height: 420 };

interface Quote {
  symbol: string;
  company: string;
  bid: number;
  ask: number;
  volume: number;
}

const COMPANIES = [
  ['NWND', 'Northwind Traders'],
  ['KSTR', 'Kestrel Logistics'],
  ['HRBR', 'Harbourline Marine'],
  ['SKRA', 'Sakura Retail Group'],
  ['LOTS', 'Lotus Electronics'],
  ['ANDS', 'Andes Coffee Co.'],
  ['RVAG', 'Rio Verde Agro'],
  ['CDST', 'Cedar & Stone'],
] as const;

const price = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

const columns: ColumnDef<Quote>[] = [
  { field: 'symbol', header: 'Symbol', width: 100 },
  { field: 'company', header: 'Company', flex: 1, minWidth: 180 },
  { field: 'bid', header: 'Bid', type: 'number', width: 100, format: (v) => price.format(Number(v)) },
  { field: 'ask', header: 'Ask', type: 'number', width: 100, format: (v) => price.format(Number(v)) },
  { field: 'volume', header: 'Volume', type: 'number', width: 120 },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const random = seededRandom(42);
  const quotes = new Map<string, Quote>(
    COMPANIES.map(([symbol, company]) => {
      const bid = 20 + Math.round(random() * 18000) / 100;
      return [symbol, { symbol, company, bid, ask: bid + 0.05, volume: 0 }];
    }),
  );
  const grid = createGrid<Quote>(body, {
    columns,
    rows: [...quotes.values()],
    getRowId: (quote) => quote.symbol,
    theme: docsTheme(),
    ariaLabel: 'Live quotes',
  });

  const pending = new Map<string, Quote>();
  let frame = 0;
  let applied = 0;
  const flush = () => {
    frame = 0;
    const update = [...pending.values()];
    pending.clear();
    grid.applyTransaction({ update });
    grid.flashCells({ rows: update, columns: ['bid', 'ask', 'volume'] });
    applied += update.length;
    status.textContent = `${applied} updates applied in batches, one transaction per frame.`;
  };
  const receive = (quote: Quote) => {
    pending.set(quote.symbol, quote);
    if (!frame) frame = requestAnimationFrame(flush);
  };

  let timer: ReturnType<typeof setInterval> | undefined;
  const tick = () => {
    for (let i = 0; i < 3; i++) {
      const [symbol] = COMPANIES[Math.floor(random() * COMPANIES.length)];
      const current = pending.get(symbol) ?? quotes.get(symbol)!;
      const bid = Math.max(1, Math.round((current.bid + (random() - 0.5)) * 100) / 100);
      const next = { ...current, bid, ask: bid + 0.05, volume: current.volume + Math.ceil(random() * 500) };
      quotes.set(symbol, next);
      receive(next);
    }
  };
  const start = () => {
    if (timer === undefined) timer = setInterval(tick, 250);
  };
  const stop = () => {
    clearInterval(timer);
    timer = undefined;
  };
  toolbar.append(button('Start feed', start), button('Pause feed', stop));
  status.textContent = 'Start the feed to stream quotes into the grid.';

  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    stop();
    if (frame) cancelAnimationFrame(frame);
    stopTheme();
    grid.destroy();
  };
}
```

## 1. Create the grid with stable ids

```ts title="quotes-grid.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

export interface Quote {
  symbol: string;
  company: string;
  bid: number;
  ask: number;
  volume: number;
}

const price = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

const columns: ColumnDef<Quote>[] = [
  { field: 'symbol', header: 'Symbol', width: 100 },
  { field: 'company', header: 'Company', flex: 1 },
  { field: 'bid', header: 'Bid', type: 'number', format: (v) => price.format(Number(v)) },
  { field: 'ask', header: 'Ask', type: 'number', format: (v) => price.format(Number(v)) },
  { field: 'volume', header: 'Volume', type: 'number' },
];

export const grid = createGrid<Quote>(document.querySelector<HTMLElement>('#quotes')!, {
  columns,
  rows: await loadSnapshot(),
  getRowId: (quote) => quote.symbol,
  flashDuration: 600,
});
```

`getRowId` is what lets a transaction find the row to update. Without it, row ids are positions, and an update cannot be matched to the row it belongs to.

## 2. Batch messages per frame

```ts title="quotes-stream.ts"
import { grid, type Quote } from './quotes-grid';

type QuoteMessage =
  | { type: 'quote'; quote: Quote }
  | { type: 'listed'; quote: Quote }
  | { type: 'delisted'; symbol: string };

const updates = new Map<string, Quote>();
const added: Quote[] = [];
const removed = new Set<string>();
let frame = 0;

function flush(): void {
  frame = 0;
  const update = [...updates.values()];
  grid.applyTransaction({ add: added.splice(0), update, remove: [...removed] });
  grid.flashCells({ rows: update, columns: ['bid', 'ask', 'volume'] });
  updates.clear();
  removed.clear();
}

function schedule(): void {
  if (!frame) frame = requestAnimationFrame(flush);
}

const socket = new WebSocket('wss://quotes.example.com/stream');

socket.addEventListener('message', (event) => {
  const message = JSON.parse(event.data) as QuoteMessage;
  if (message.type === 'quote') updates.set(message.quote.symbol, message.quote);
  else if (message.type === 'listed') added.push(message.quote);
  else removed.add(message.symbol);
  schedule();
});
```

A `Map` keyed by id keeps only the latest message per row, so 50 ticks for one symbol within a frame become one update.

## How it works

- `applyTransaction({ add, update, remove })` adds rows, replaces rows with the same id, and removes rows given as objects or ids. Sorting, filtering and grouping are reapplied to the result.
- Selection, focus and expansion are kept, because they are stored by row id.
- `flashCells()` briefly highlights the given cells. Its duration comes from `flashDuration` (500 ms by default) or the `duration` parameter. Set `flashCells: true` to flash every cell changed by an edit or `setValue()` automatically; transactions are flashed only when you call `flashCells()`.
- When a sort is active, an updated row moves to its new position. If rows jumping around is distracting, pause the stream while the user hovers or edits, or remove the sort.

## Pitfalls

- **Do not mutate rows in place** and expect a redraw. Pass a new object in `update`, or call `refresh()` after mutating.
- **Updates for unknown ids are ignored.** Send a `listed` message, or use `add`, for new rows.
- **Hidden tabs.** `requestAnimationFrame` does not run in background tabs, so messages pile up in the map, which is fine: the next visible frame applies them in one transaction.
- **Close the socket** when the grid is destroyed, and cancel a pending frame with `cancelAnimationFrame`.

## Related

- [Updating data](https://docs.birchui.com/grid/updating-data.md), including [Streaming updates](https://docs.birchui.com/grid/updating-data.md#streaming-updates).
- [Show a million rows](https://docs.birchui.com/recipes/grid-million-rows.md).
- [`RowTransaction`](https://docs.birchui.com/api/core.md) in the API reference.
