EntityStore: onChange() method

Available since @irtio/client 5.0BrowsersNode

The onChange() method of the EntityStore interface calls a function each time fields of an entity of a kind change, with the names of the fields that changed.

Syntax

onChange(kind, callback)
onChange(kind, callback, options)

Parameters

kind
A kind declared in the client’s schema, such as schema.state for the shared state.
callback

A function called with these parameters:

entity
The ClientEntity that changed, typed as its kind.
changed
An array of the names of the fields that changed.
options Optional

An object with this property:

signal
An AbortSignal. When it aborts, the callback is removed, as addEventListener() removes a listener. If it has aborted already, the callback isn’t added.

Return value

A function that removes the callback.

Exceptions

Error
Thrown if the kind isn’t declared in the client’s schema.

Description

The callback runs once the whole state update is applied, for the changes the room sent in it. It doesn’t run for an entity’s values when it enters; onEnter() gets those.

The local player’s own writes to an entity it owns don’t call it: the client’s copy changes at once, and the room’s echo of the same value changes nothing. When the room overrules a write, the correction calls onChange() for the corrected fields, then onCorrect().

The shared state and private state are entities too, so onChange(schema.state, callback) follows the shared state.

Examples

Redrawing the score when it changes

The shared state holds both teams’ scores and the clock. The client redraws the scoreboard only when a score changes.

// scoreboard.ts
import { connect, defineSchema, entity } from "@irtio/client";

const Match = entity("match", { home: "u8", away: "u8", clock: "u16" });
const schema = defineSchema({ state: Match });

const room = await connect("final", { schema });

room.entities.onChange(schema.state, (match, changed) => {
  if (changed.includes("home") || changed.includes("away")) console.log(`${match.home} : ${match.away}`);
});

See also

Runtime availability

BrowsersNode
onChange()5.05.0