gridcn2.0.0
Data modes

Fetch with a cache

Put a fetch cache such as TanStack Query or SWR between the grid and your API, for a plain array, pages, or scroll blocks.

The grid does not care where its rows come from. A fetch library plugs into one place in each data mode. Its cache then serves repeat requests. gridcn installs no fetch library, so add @tanstack/react-query or swr to your app first. TanStack Query also needs a QueryClientProvider above the grid.

Cache a whole array

useQuery fetches the rows. onDataChange writes each change into the same queryKey, and onSave sends it to the API through one useMutation:

"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  DataGrid,
  defineColumns,
  type DataChange,
} from "@/components/data-grid/data-grid";
type Order = { id: string; customer: string };
const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer" },
]);

export function OrdersGrid() {
  const queryClient = useQueryClient();
  const orders = useQuery<Order[]>({
    queryKey: ["orders"],
    queryFn: () => fetch("/api/orders").then((response) => response.json()),
  });
  const save = useMutation({
    mutationFn: async (change: DataChange<Order>) => {
      const response = await fetch("/api/orders", {
        method: "POST",
        body: JSON.stringify(change.ops),
      });
      if (!response.ok) throw new Error(`Save failed: ${response.status}`);
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ["orders"] }),
  });
  return (
    <DataGrid
      data={orders.data ?? []}
      columns={columns}
      getRowId={(row) => row.id}
      onDataChange={(next) => queryClient.setQueryData(["orders"], next)}
      onSave={(change) => save.mutateAsync(change)}
    />
  );
}

The grid shows each change at once, and onDataChange keeps the cache in step. If the request fails, the grid reverts the change and calls onDataChange again with the reverted rows. See Revert or refetch after a save.

Edits are server state. onSave sends each change, and onDataChange writes the cache. The invalidation then shows what the server holds. With SWR, call the mutate that useSWR returns in place of invalidateQueries.

A socket or a poll can push values many times per second. Write such values with updateCells, not with a new data array. See Push live values.

Cache scroll blocks

  • Call queryClient.fetchQuery inside fetchRows.
  • Key the query by serverSpecKey(spec), start, and end.
  • Resolve queryFn with { rows, totalRowCount }.

fetchRows is a plain function that returns a promise. A cache pays off for blocks that the grid unloads and the user scrolls back to. Above maxLoadedRows, the hook unloads the blocks viewed longest ago. A sequential source unloads the blocks furthest from the rendered rows. refresh() unloads every block outside the rendered rows. You can evict a row range yourself too.

Key each block

Make each block one query. Include the spec in the key, so a new sort never reads old blocks:

"use client";

import { useQueryClient } from "@tanstack/react-query";
import {
  DataGrid,
  defineColumns,
  serverSpecKey,
} from "@/components/data-grid/data-grid";
import {
  useDataGridServerRows,
} from "@/components/data-grid-server/data-grid-server";

type Order = { id: string; customer: string };
const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer" },
]);

export function OrdersGrid() {
  const queryClient = useQueryClient();
  const server = useDataGridServerRows<Order>({
    mode: "scroll",
    fetchRows: ({ spec, start, end }) =>
      queryClient.fetchQuery({
        queryKey: ["orders", serverSpecKey(spec), start, end],
        staleTime: 60_000,
        queryFn: async ({ signal: querySignal }) => {
          const response = await fetch("/api/orders/query", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ spec, start, end }),
            signal: querySignal,
          });
          const answer = await response.json();
          return { rows: answer.rows, totalRowCount: answer.total };
        },
      }),
  });
  return <DataGrid {...server.gridProps} columns={columns} />;
}

staleTime sets how long a cached block counts as fresh. An evicted block that scrolls back within that time reads from the cache, and the network stays quiet. Evict whole blocks, in multiples of blockSize, so the refetch asks for the same start and end as the cached query.

queryFn uses the signal of TanStack Query, not the signal of the request. A spec change aborts the request signal, but the fetch runs on and fills the cache. The hook ignores its late answer.

fetchRows runs again on server.refresh(). A scroll-mode refresh() fetches the rendered rows and drops every other loaded row. The hook also refreshes by itself when saves settle (refreshAfterSave, default "settled"), in pages and in scroll mode, once onSave returns promises. In pages mode and random access it also refreshes after a row operation and after the last pending insert or delete save settles.

Those refreshes go through fetchQuery too, so they get the cached blocks while those are fresh. To reach the server, pass staleTime: 0 to fetchQuery when request.reason is not "load". The reason of a request is "load", "refresh", "save", or "retry". The hook sends it to nobody. Or call queryClient.invalidateQueries({ queryKey: ["orders"] }) before a manual refresh().

With SWR, call preload(key, fetcher) from swr in place of fetchQuery. preload keeps each block, loaded or failed, until a useSWR call with the same key reads it. It has no staleTime. A global mutate(key) clears the entry of a block. Until you call it, refresh() and retry() get the same answer again. Every fetched block stays in memory. For scroll mode, prefer a cache with staleTime and invalidation.

Cache pages

With useDataGridServerRows in pages mode, call queryClient.fetchQuery inside fetchRows as in Cache scroll blocks. Key the query by serverSpecKey(spec), page, and pageSize.

With useDataGridServerPager and your own fetch, use the page, the page size, and the spec as the query key. keepPreviousData keeps the old page on screen while the next one loads:

"use client";

import { useState } from "react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import {
  DataGrid,
  defineColumns,
  type FilterNode,
  type SortSpec,
} from "@/components/data-grid/data-grid";
import {
  DataGridPaginationBar,
  useDataGridServerPager,
} from "@/components/data-grid-pagination/data-grid-pagination";

type Order = { id: string; customer: string };
type Spec = { sorts: SortSpec[]; filters: FilterNode[]; searchText: string };
const NO_SPEC: Spec = { sorts: [], filters: [], searchText: "" };
const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer" },
]);

export function OrdersGrid() {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(25);
  const [spec, setSpec] = useState<Spec>(NO_SPEC);
  const query = useQuery<{ rows: Order[]; total: number }>({
    queryKey: ["orders", page, pageSize, spec],
    queryFn: async ({ signal }) => {
      const response = await fetch("/api/orders/query", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ page, pageSize, ...spec }),
        signal,
      });
      return response.json();
    },
    placeholderData: keepPreviousData,
  });
  function changeSpec(change: Partial<Spec>) {
    setSpec({ ...spec, ...change });
    setPage(1);
  }
  const { pager } = useDataGridServerPager({
    page,
    pageSize,
    totalRowCount: query.data?.total ?? null,
    onPageChange: setPage,
    onPageSizeChange: (next) => {
      setPageSize(next);
      setPage(1);
    },
  });
  return (
    <>
      <DataGrid
        data={query.data?.rows ?? []}
        columns={columns}
        getRowId={(row) => row.id}
        sortState={spec.sorts}
        onSortChange={(sorts) => changeSpec({ sorts })}
        filterState={spec.filters}
        onFilterChange={(filters) => changeSpec({ filters })}
        searchText={spec.searchText}
        onSearchTextChange={(searchText) => changeSpec({ searchText })}
        totalRowCount={query.data?.total ?? null}
      />
      <DataGridPaginationBar {...pager} />
    </>
  );
}

totalRowCount makes the grid leave the sort and filter to your server, so the controlled spec reaches the key and the request. Load rows by page shows the same wiring without a cache.

With SWR, replace useQuery with useSWR. The fetcher receives the key itself, so the key is a tuple:

const { data } = useSWR<{ rows: Order[]; total: number }>(
  ["orders", page, pageSize, spec],
  ([, current, size, currentSpec]: [string, number, number, Spec]) =>
    fetch("/api/orders/query", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ page: current, pageSize: size, ...currentSpec }),
    }).then((r) => r.json()),
  { keepPreviousData: true },
);

A useSWR call revalidates on window focus and on reconnect by default. Set revalidateOnFocus: false and revalidateOnReconnect: false to stop them.

On this page