Real Data Integration

<GraphCanvas> doesn't fetch data — you do, and you call api.nodes.add / api.edges.add to inject it. This page shows the three common shapes: fetch on mount, paginated streaming, and two-way sync with an external store (Redux / Zustand / URL).

Pattern 1 — fetch JSON, add once

The simplest case: load a static dataset on mount.

import { useRef, useEffect } from "react";
import { GraphCanvas, type RenderEngineApi } from "@kineviz/gl";

export function Graph() {
  const apiRef = useRef<RenderEngineApi>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const res = await fetch("/data/karate-club.json");
      const { nodes, edges } = await res.json();
      if (cancelled) return;

      const api = apiRef.current;
      if (!api) return;
      await api.nodes.add(nodes);
      await api.edges.add(edges);
      await api.camera.flyToAll();
    })();
    return () => { cancelled = true; };
  }, []);

  return <GraphCanvas apiRef={apiRef} forceLayout />;
}

The apiRef is populated synchronously on mount but the engine itself needs a frame to fully wire up. The flyToAll() call waits internally — no extra await tick needed.

Pattern 2 — paginated streaming

For datasets bigger than memory, page through a server endpoint and add each page incrementally. api.nodes.add / api.edges.add are batched and emit a single graph:deltaApplied event per call, so per-page adds are cheap.

useEffect(() => {
  let cancelled = false;
  (async () => {
    const api = apiRef.current;
    if (!api) return;

    let cursor: string | null = null;
    while (!cancelled) {
      const res = await fetch(`/api/graph?cursor=${cursor ?? ""}`);
      const { nodes, edges, nextCursor } = await res.json();
      if (cancelled) break;

      await api.nodes.add(nodes);
      await api.edges.add(edges);

      if (!nextCursor) break;
      cursor = nextCursor;
    }

    if (!cancelled) await api.camera.flyToAll();
  })();
  return () => { cancelled = true; };
}, []);

The cancelled ref pattern prevents writes after unmount. With React StrictMode (dev), useEffect runs twice — cancelled ensures the first run's pending fetches don't pollute the second run's graph.

Pattern 3 — two-way sync with an external store

When your host owns the data (Redux, a backend mirror, a URL parameter), mirror it into the engine on prop changes and listen to engine mutations to update the store:

import { useEffect, useRef } from "react";
import { GraphCanvas, type RenderEngineApi, type GraphDelta } from "@kineviz/gl";

export function GraphView({ store }: { store: GraphStore }) {
  const apiRef = useRef<RenderEngineApi>(null);

  // Push: external store → engine (on mount + when host data changes)
  useEffect(() => {
    const api = apiRef.current;
    if (!api) return;
    api.data.setData({ nodes: store.nodes, edges: store.edges });
  }, [store.version]);

  // Pull: engine → external store (on every batched mutation)
  const onDelta = (delta: GraphDelta) => {
    store.applyDelta(delta);
  };

  return <GraphCanvas apiRef={apiRef} onDelta={onDelta} forceLayout />;
}

The onDelta callback fires once per batched mutation with the rich engine delta shape (addedNodes, updatedNodes, removedNodeIds, plus edges + position patches + metadata). Mirror as much or as little as you need.

Echo loop avoidance: if your store.applyDelta would round-trip back into a prop change that calls api.data.setData again, you'll ping-pong. Either gate the round trip with a graph:dataReset event debounce, or compare versions before re-pushing.

Loading from common formats

Neo4j / Bolt result

A RecordList from neo4j-driver exposes _fields per record. Map node records to NodeData and edge records to EdgeData:

const result = await session.run("MATCH (n)-[r]->(m) RETURN n, r, m LIMIT 1000");

const nodeMap = new Map<string, any>();
const edges: any[] = [];

for (const record of result.records) {
  const [n, r, m] = record._fields;
  for (const node of [n, m]) {
    const id = node.identity.toString();
    if (!nodeMap.has(id)) {
      nodeMap.set(id, {
        id,
        category: node.labels[0] ?? "Node",
        properties: node.properties,
      });
    }
  }
  edges.push({
    id: r.identity.toString(),
    source: r.start.toString(),
    target: r.end.toString(),
    relationship: r.type,
    properties: r.properties,
  });
}

await api.nodes.add([...nodeMap.values()]);
await api.edges.add(edges);

GraphQL

Most GraphQL graph schemas return a { nodes, edges } shape directly — pass to add as-is. For nested adjacency-list shapes:

const { data } = await client.query({ query: GET_NETWORK });
const nodes = data.network.people.map((p: any) => ({
  id: p.id,
  category: p.role,
  properties: { name: p.name },
}));
const edges = data.network.people.flatMap((p: any) =>
  p.knows.map((target: any) => ({
    id: `${p.id}->${target.id}`,
    source: p.id,
    target: target.id,
  })),
);
await api.nodes.add(nodes);
await api.edges.add(edges);

CSV

Browser fetch + Papa.parse (or any CSV lib) → array of objects → pass to add:

const res = await fetch("/data/people.csv");
const csv = await res.text();
const { data } = Papa.parse(csv, { header: true, dynamicTyping: true });
await api.nodes.add(data);

Refreshing data

To wholesale replace the graph (e.g. user switches dataset), use api.data.setData. It clears the existing graph in one call and seeds the new one:

async function switchDataset(name: string) {
  const res = await fetch(`/data/${name}.json`);
  const { nodes, edges } = await res.json();
  await api.data.setData({ nodes, edges });
  await api.camera.flyToAll();
}

This fires a single graph:dataReset event (separate from per-mutation graph:deltaApplied).

See also