Skip to content

Function: composeGuards()

API / @xmachines/play-xstate / composeGuards

function composeGuards<TContext, TEvent>(guards): ComposedGuard;

Defined in: packages/play-xstate/src/guards/compose.ts:100

Composes the guards with the AND logic, through the and() helper of XState

The function joins more than one guard predicate with the AND semantics: every guard must pass, and the composition then succeeds. It uses the built-in and() helper of XState. The type inference and the serialization of the machine are therefore correct.

Architectural context: the function supports Actor Authority (INV-01), because it composes the guards of a state machine transition declaratively. A guard enforces a rule of the business logic, and that rule decides if a navigation or an action is valid.

Type Parameters

Type ParameterDefault typeDescription
TContextanyThe context type of the state machine
TEventanyThe event type

Parameters

ParameterTypeDescription
guardsGuardArray<TContext, TEvent>The array of the guard predicates, or of the guard names as strings

Returns

ComposedGuard

The and() guard composition of XState

Throws

When the array of the guards is empty

Examples

An AND composition with named guards

import { setup } from "xstate";
import { composeGuards } from "@xmachines/play-xstate";
const machine = setup({
guards: {
isLoggedIn: ({ context }) => !!context.userId,
hasPermission: ({ context }) => context.permissions.includes("admin"),
},
}).createMachine({
on: {
accessAdmin: {
// Both guards must pass
guard: composeGuards(["isLoggedIn", "hasPermission"]),
target: "adminPanel",
},
},
});

An AND composition with inline predicates

import { composeGuards } from "@xmachines/play-xstate";
guard: composeGuards([({ context }) => context.age >= 18, ({ context }) => context.verified]);

See

Deprecated

Use the and(), or(), and not() combinators of XState directly. This helper does not compose with a guard slot that setup() types, and the next major version removes it.