Skip to content
GitHubXDiscord

useAction

Stable · since 0.1.0

Registers an action handler — the function the runtime invokes when a trigger handler calls actions.<name>(payload). Handlers can be sync or async; their return value is awaited inside the trigger handler’s run.

import { useAction } from '@triggery/react';
function useAction<S extends TriggerSchema, K extends ActionKey<S>>(
  trigger: Trigger<S>,
  name: K,
  handler: ActionMap<S>[K] extends void
    ? () => void | Promise<void>
    : (payload: ActionMap<S>[K]) => void | Promise<void>,
): void;

The handler’s payload parameter is typed from the action schema. Void-payload actions register a () => void | Promise<void> handler.

ParamTypeDescription
triggerTrigger<S>The trigger returned by createTrigger.
nameK extends ActionKey<S>An action declared in the trigger’s schema.
handlerFunctionSync or async handler. May return void or Promise<void>.

void. The handler is held in a ref and the registration is set up in useEffect / cleaned up on unmount.

import { createTrigger } from '@triggery/core';
import { useAction } from '@triggery/react';

const trigger = createTrigger<{
  events:  { 'new-message': { author: string } };
  actions: { showToast: { title: string; body: string } };
}>({
  id: 'demo',
  events: ['new-message'],
  handler({ event, actions }) {
    actions.showToast?.({ title: event.payload.author, body: 'hi' });
  },
});

function NotificationLayer() {
  useAction(trigger, 'showToast', ({ title, body }) => {
    // ^^^^^ payload is typed from the schema
    console.log('toast', title, body);
  });
  return null;
}

The runtime drives the trigger handler — and therefore your async action — under the trigger’s concurrency strategy. For take-latest the AbortSignal in your trigger handler’s ctx is the one to pass downstream; if your action also wants its own abort, plumb a controller in.

import { createTrigger } from '@triggery/core';
import { useAction } from '@triggery/react';

const trigger = createTrigger<{
  events: { 'submit-form': { url: string; body: unknown } };
  actions: { post: { url: string; body: unknown } };
}>({
  id: 'demo',
  events: ['submit-form'],
  async handler({ event, actions, signal }) {
    await actions.post?.(event.payload);
    signal.throwIfAborted();
  },
});

function Network() {
  useAction(trigger, 'post', async ({ url, body }) => {
    await fetch(url, { method: 'POST', body: JSON.stringify(body) });
  });
  return null;
}

If you mount two components both calling useAction(trigger, 'showToast', …), the most recently mounted wins, and a DEV warn-once is logged. On unmount the previous handler is restored. See Ownership.