[**Documentation**](../../../../README)

***

[Documentation](../../../../README) / [@zerotal/orm](../../README) / [index](../README) / State

# Function: State()

> **State**\<`TBase`\>(`Base`): \{(...`args`): `State`; `stateField`: `string`; `states?`: `Record`\<`string`, [`StateDefinition`](../interfaces/StateDefinition)\<`string`, `any`\>\>; `onTransition`: `void`; `prototype`: `State`\<`any`\>; \} & `TBase`

Defined in: [packages/orm/src/model/State.ts:144](https://github.com/zerotaldev/zerotal/blob/1d6fb26b05b18ba077de1bfaeb46c42131cd8b70/packages/orm/src/model/State.ts#L144)

Mixin that adds finite-state-machine behaviour to a model. Compose it so only
models that declare a workflow carry the API — `transitionTo` / `forceState` /
`onTransition` and the `states` + `stateField` statics never appear on models
that don't use them.

Declare the machine in `static states` (use `as const` for exact state typing)
and, optionally, override `static stateField` when the state column isn't
`status`. Each transition validates that the move is allowed, runs the target
state's guard, persists via `save()`, then fires `onTransition` callbacks.

## Type Parameters

### TBase

`TBase` *extends* [`Constructor`](../type-aliases/Constructor)

## Parameters

### Base

`TBase`

## Returns

## Example

```ts
const States = {
  pending:   { canTransitionTo: ["active", "cancelled"] as const },
  active:    { canTransitionTo: ["expired"] as const,
               guard: (s: Subscription) => { if (!s.stripeId) throw new StateError(...); } },
  expired:   { canTransitionTo: [] as const },
  cancelled: { canTransitionTo: [] as const },
} as const;

class Subscription extends BaseModelWith(State) {
  static states = States;
  @column() status!: keyof typeof States;
}

const [ok, err] = await sub.transitionTo("active");
if (!ok) return json({ error: err.message }, 422);
```
