---
url: /pawn/docs/packages/data.md
description: Feeds that keep one entity per item of an API or WebSocket stream.
---

# @pawnjs/data

::: info Not on npm yet
This package comes with a later release of Pawn.
:::

Data streams as entities: one entity per item of an API response, a
WebSocket or anything you push. `@pawnjs/data` imports no three.js and no DOM;
it needs `@pawnjs/core` and `koota`.

```ts
import { Feed, poll, smoothTo } from "@pawnjs/data";

interface Vehicle {
  id: string;
  x: number;
  z: number;
}

const vehicles = new Feed<Vehicle>({
  key: (v) => v.id,
  spawn: (v, engine) => engine.spawn(Visual(truck())),
  update: (entity, v) => smoothTo(entity, { x: v.x, z: v.z }),
  source: poll(() => fetch("/api/vehicles").then((r) => r.json()), { every: 2 }),
});
engine.use(vehicles);
```

Deliveries are queued and applied first in the `input` phase (right after
`Input`), so every system in a frame sees the same data, whenever the
response arrived. `spawn` runs for a key seen for the first time and
`update` for every item, new ones included.

## Feed options

| Option | Default | Meaning |
|---|---|---|
| `key` | (required) | Identity of an item; one entity per key. |
| `spawn` | (required) | `(item, engine)`: creates the entity of a new key, e.g. `engine.spawn("truck")` for a prefab, or returns an existing one (an entity the scene built). Returning `undefined` skips the item. |
| `update` | none | Writes an item into its entity. |
| `remove` | destroy | Lets go of the entity of a key that is gone. |
| `source` | none | Delivers items while the feed is installed. |
| `mode` | `"replace"` | `"replace"`: each delivery is the whole set and missing keys are removed. `"patch"`: deliveries add and change only. |
| `onError` | `console.warn` | Called with errors a source reports, and with an error `spawn` or `update` throws for one item, which is skipped. |
| `name` | none | Shown in the plugin name, for debugging, and the start of entity ids. |
| `id` | `"<name>/<key>"` | [`EntityId`](/guide/snapshots#entity-ids) of a key's entity; without `id` or `name`, entities get none. |

With an id, a feed's entities are saved by [snapshots](/guide/snapshots).
An entity that already has the key's id, such as one restored from a
snapshot, is taken over instead of spawning another. `spawn` is not called
for it, so add what a snapshot does not save (a `Visual`) in `update`, or
draw with `Shape` or `Model`. Ids must differ between keys and between
feeds.

In replace mode only the latest undelivered delivery is applied; in patch
mode every delivery is applied in order.

## Reading and writing a feed

* `feed.push(items)` delivers by hand, like a source does.
* `feed.remove(keys)` removes keys at the next frame.
* `feed.entity(key)` returns the entity of a key; `feed.keys()` and
  `feed.size` list them.
* `feed.version` grows with every applied delivery, for cheap change checks.
* `feed.dispose()` stops the source and lets go of the entities before the
  engine is disposed, e.g. when a React effect cleans up.

## Sources

A source is a function that gets a sink (`push(items)`, `error(e)`) and
returns a function that stops it. Two come with the package:

```ts
// Calls the fetcher, then again `every` seconds after it settles.
poll((signal) => fetch(url, { signal }).then((r) => r.json()), { every: 5 });

// Delivers each message; reconnects `retry` seconds after a close.
websocket("wss://example.com/live", (data) => JSON.parse(String(data)).items, {
  retry: 2,
});
```

A failed fetch or a message that does not parse is reported to `onError`
and the source keeps going. One response can feed several feeds: call a
source with your own sink and `push` into each.

## Smooth movement

Data that arrives every few seconds would make entities jump. `smoothTo`
sets a `Smooth` target instead of `Position`; the first call places the
entity at once, later ones let it ease there with `halfLife` (seconds to
cover half of the way, default 0.3). The first `Smooth` installs the
`Smoothing` plugin, with or without a feed. It runs on unscaled time.

The [Energy flow](https://jakubprill.github.io/pawn/energy.html) example
polls two endpoints of a simulated backend into its scene's nodes and links.
