EntityStore: onCorrect() method

Available since @irtio/client 5.0BrowsersNode

The onCorrect() method of the EntityStore interface calls a function each time the room overrules the local player’s writes to an entity of a kind it owns, with the names of the corrected fields.

Syntax

onCorrect(kind, callback)
onCorrect(kind, callback, options)

Parameters

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

A function called with these parameters:

entity
The OwnedEntity the room corrected, typed as its kind, with the room’s values.
corrected
An array of the names of the writable fields the room corrected.
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 owner of an entity keeps its own values for the writable fields it owns. When the room’s value differs from what the owner wrote, because the room’s writes handler clamped or rejected the write or room code wrote the field, the owner gets a correction:

  • It overwrites the client’s copy with the room’s value and drops the client’s unsent writes to those fields.
  • onChange() runs for the fields first, then onCorrect().
  • Every other client sees only the room’s value, and never a correction.

Use onCorrect() to snap or smooth what the player sees to the room’s value, or to tell the player why a move didn’t take.

Examples

Snapping a paddle back to the room’s position

The player drags their paddle, and the room clamps it to the table. When the room corrects it, the client moves the paddle’s sprite to the room’s value.

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

const Paddle = entity("paddle", { y: "f32" }, { writable: ["y"] });
const schema = defineSchema({ entities: [Paddle] });

const room = await connect("pong-7", { schema });

room.entities.onCorrect(Paddle, (paddle, corrected) => {
  if (corrected.includes("y")) console.log(`snap paddle ${paddle.id} to ${paddle.y}`);
});

See also

Runtime availability

BrowsersNode
onCorrect()5.05.0