Back to Copilotkit

bind

showcase/shell-docs/src/content/reference/bot/functions/bind.mdx

1.60.12.4 KB
Original Source

Overview

Inline handlers (onClick and friends) are bound by content — component identity + path + serializable props — so the engine can re-derive a handler after a restart by re-rendering the component. bind attaches a small args payload to a handler: on dispatch, the handler receives args via ctx.action.value, and the payload is snapshotted alongside the minted action id in the ActionStore.

Signature

ts
import { bind } from "@copilotkit/bot-ui";

function bind(handler: ClickHandler, args: unknown): ClickHandler;

Parameters

<PropertyReference name="handler" type="ClickHandler" required> The handler to run on dispatch. Receives the normal [`InteractionContext`](/reference/bot/types/InteractionContext), with `ctx.action.value` set to `args`. </PropertyReference> <PropertyReference name="args" type="unknown" required> The payload handed back to the handler as `ctx.action.value`. Keep it **small** — it's snapshotted with the action (see the v1 caveat under Behavior). </PropertyReference>

Usage

tsx
import { bind } from "@copilotkit/bot-ui";
import type { ClickHandler } from "@copilotkit/bot-ui";

const handleChoice: ClickHandler = async ({ thread, action }) => {
  await thread.post(`You chose ${JSON.stringify(action.value)}.`);
};

<Button onClick={bind(handleChoice, { choiceId: "abc123" })}>Choose</Button>;

Behavior

  • The returned handler is tagged; when the engine binds the tree, it stores args in the action snapshot (boundArgs), and the hot-path dispatch hands args back via ctx.action.value.
  • v1 caveat: the cold path (cache miss → snapshot rehydration) re-renders the component from its frozen props and uses the re-created handler — the persisted boundArgs is not yet injected on rehydration. In practice that means args must currently be derivable from the component's props to survive a restart; treat restart-proof bind args as not-yet-supported.
  • Prefer plain inline handlers when the data is already in the component's props — bind is for handler-specific payloads you don't want to thread through props.