Skip to content

Function: negateGuard()

API / @xmachines/play-xstate / negateGuard

function negateGuard<TContext, TEvent>(guard): ComposedGuard;

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

Negates a guard, through the not() helper of XState

The function inverts the result of a guard: the guard passes, and NOT then fails; the guard fails, and NOT then passes. It uses the built-in not() helper of XState, and the serialization is therefore correct.

Type Parameters

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

Parameters

ParameterTypeDescription
guardstring | Guard<TContext, TEvent>The guard predicate to negate, or its name

Returns

ComposedGuard

The not() guard negation of XState

Example

A NOT composition with a named guard

import { setup } from "xstate";
import { negateGuard } from "@xmachines/play-xstate";
const machine = setup({
guards: {
isGuest: ({ context }) => !context.userId,
},
}).createMachine({
on: {
accessDashboard: {
// Permit the transition when the user is NOT a guest, which means an authenticated user
guard: negateGuard("isGuest"),
target: "dashboard",
},
},
});

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.