Skip to main content
Module

x/xstate/src/actors/transition.ts>fromTransition

Actor-based state management & orchestration for complex app logic.
Go to Latest
function fromTransition
import { fromTransition } from "https://deno.land/x/xstate@xstate%405.9.1/src/actors/transition.ts";

Returns actor logic given a transition function and its initial state.

A “transition function” is a function that takes the current state and received event object as arguments, and returns the next state, similar to a reducer.

Actors created from transition logic (“transition actors”) can:

  • Receive events
  • Emit snapshots of its state

The transition function’s state is used as its transition actor’s context.

Note that the "state" for a transition function is provided by the initial state argument, and is not the same as the State object of an actor or a state within a machine configuration.

Examples

Example 1

const transitionLogic = fromTransition(
  (state, event) => {
    if (event.type === 'increment') {
      return {
        ...state,
        count: state.count + 1,
      };
    }
    return state;
  },
  { count: 0 },
);

const transitionActor = createActor(transitionLogic);
transitionActor.subscribe((snapshot) => {
  console.log(snapshot);
});
transitionActor.start();
// => {
//   status: 'active',
//   context: { count: 0 },
//   ...
// }

transitionActor.send({ type: 'increment' });
// => {
//   status: 'active',
//   context: { count: 1 },
//   ...
// }

Type Parameters

TContext
TEvent extends EventObject
TSystem extends AnyActorSystem
TInput extends NonReducibleUnknown
optional
TEmitted extends EventObject = EventObject

Parameters

transition: () => TContext

The transition function used to describe the transition logic. It should return the next state given the current state and event. It receives the following arguments:

  • state - the current state.
  • event - the received event.
  • actorScope - the actor scope object, with properties like self and system.
initialContext: TContext | ((unnamed 0: { input: TInput; self: TransitionActorRef<TContext, TEvent>; }) => TContext)

The initial state of the transition function, either an object representing the state, or a function which returns a state object. If a function, it will receive as its only argument an object with the following properties:

  • input - the input provided to its parent transition actor.
  • self - a reference to its parent transition actor.