### Run TodoMVC React Example Locally Source: https://github.com/statelyai/xstate/blob/main/examples/todomvc-react/readme.md Use these commands to install dependencies and start the development server for the TodoMVC React example. ```shell cd examples/todomvc-react pnpm install pnpm run dev ``` -------------------------------- ### Install and Run Workflow Engine Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md Commands to set up dependencies and start the local development server. ```bash pnpm install pnpm start ``` -------------------------------- ### Vue Quickstart with createStore and useSelector Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-vue/README.md Demonstrates basic usage of @xstate/store-vue by creating a store with a counter and displaying its value using useSelector. This example shows how to define store state, actions, and subscribe to state changes in a Vue component. ```vue ``` -------------------------------- ### Preview the project Source: https://github.com/statelyai/xstate/blob/main/examples/readme.md Start the development server to preview the demo. ```bash pnpm run dev ``` -------------------------------- ### Install @xstate/store-react Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md Install the package using npm. ```bash npm install @xstate/store-react ``` -------------------------------- ### Install @xstate/solid Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md Install the required packages via npm. ```bash npm i xstate @xstate/solid ``` -------------------------------- ### Install xstate and @xstate/vue Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-vue/README.md Install the necessary packages using npm. ```bash npm i xstate @xstate/vue ``` -------------------------------- ### Install @xstate/store-solid Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-solid/README.md Install the Solid.js adapter for @xstate/store using npm. ```bash npm install @xstate/store-solid ``` -------------------------------- ### Install @xstate/store-svelte Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-svelte/README.md Install the @xstate/store-svelte package using npm. ```bash npm install @xstate/store-svelte ``` -------------------------------- ### Install XState Source: https://github.com/statelyai/xstate/blob/main/README.md Command to install the core XState package. ```bash npm install xstate ``` -------------------------------- ### Install @xstate/store-preact Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-preact/README.md Install the Preact adapter for @xstate/store using npm. ```bash npm install @xstate/store-preact ``` -------------------------------- ### Start development server Source: https://github.com/statelyai/xstate/blob/main/examples/trivia-game-example/README.md Launch the development server to run the application locally. ```bash yarn dev ``` -------------------------------- ### Install @xstate/store-angular Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-angular/README.md Install the @xstate/store-angular package using npm. ```bash npm install @xstate/store-angular ``` -------------------------------- ### Quickstart: Basic Store Usage Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md Demonstrates creating a store and using useSelector to display and update a count. ```tsx import { createStore, useSelector } from '@xstate/store-react'; // ... const store = createStore({ context: { count: 0 }, on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } }); const App = () => { const count = useSelector(store, (s) => s.context.count); return ( ); }; ``` -------------------------------- ### Install @xstate/store-vue Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-vue/README.md Install the Vue adapter for @xstate/store using npm. ```bash npm install @xstate/store-vue ``` -------------------------------- ### Install @xstate/store Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md Install the @xstate/store package using npm, yarn, or pnpm. ```bash npm install @xstate/store ``` -------------------------------- ### Quickstart: Create and Use a Store in Preact Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-preact/README.md Demonstrates creating a store with initial context and actions, then using the `useSelector` hook to display and update a count in a Preact component. ```tsx import { createStore, useSelector } from '@xstate/store-preact'; // ... const store = createStore({ context: { count: 0 }, on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } }); const App = () => { const count = useSelector(store, (s) => s.context.count); return ( ); }; ``` -------------------------------- ### Quickstart: Create and Use a Store with useSelector Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-solid/README.md Demonstrates how to create a store with initial context and actions, and then use the `useSelector` hook to access and display a reactive value from the store within a Solid.js component. ```tsx import { createStore, useSelector } from '@xstate/store-solid'; // ... const store = createStore({ context: { count: 0 }, on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } }); const App = () => { const count = useSelector(store, (s) => s.context.count); return ( ); }; ``` -------------------------------- ### Install @xstate/inspect with npm or yarn Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md Install the package using your preferred package manager. ```bash npm install @xstate/inspect # or yarn add @xstate/inspect ``` -------------------------------- ### Install @xstate/svelte dependencies Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-svelte/README.md Install the required packages via npm. ```bash npm i xstate @xstate/svelte ``` -------------------------------- ### Install project dependencies Source: https://github.com/statelyai/xstate/blob/main/examples/trivia-game-example/README.md Use pnpm to install all required packages for the project. ```bash pnpm install ``` -------------------------------- ### Svelte Quickstart with XState Store Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-svelte/README.md Demonstrates a basic Svelte component using @xstate/store-svelte to manage and display a counter. It shows how to create a store, define actions, and use `useSelector` to reactively display the count. ```svelte ``` -------------------------------- ### Install xstate and @xstate/react Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-react/README.md Required dependencies for using XState with React. ```bash npm i xstate @xstate/react ``` -------------------------------- ### Install @xstate/immer dependencies Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-immer/README.md Install the required packages including immer as a peer dependency. ```bash npm install immer xstate @xstate/immer ``` -------------------------------- ### Install XState dependencies Source: https://github.com/statelyai/xstate/blob/main/examples/readme.md Add the core XState library and the relevant framework-specific package. ```bash pnpm install xstate @xstate/react ``` -------------------------------- ### Quickstart: Counter Component with @xstate/store-angular Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-angular/README.md Demonstrates creating a store and using it within an Angular component to display and increment a count. The `injectStore` function is used to subscribe to store updates. ```typescript import { Component } from '@angular/core'; import { createStore, injectStore } from '@xstate/store-angular'; // ... const store = createStore({ context: { count: 0 }, on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } }); @Component({ selector: 'app-counter', template: ` ` }) export class CounterComponent { store = store; count = injectStore(store, (s) => s.context.count); } ``` -------------------------------- ### Example Response for Workflow Creation Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-credit-check-api/README.md A successful response when a new workflow is created. ```json { "message":"New workflow created successfully", "workflowId":"uzkjyy" } ``` -------------------------------- ### Interpret logic with useMachine Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md Example of interpreting a machine using the useMachine hook. ```js // existing machine const [snapshot, send] = useMachine(machine); ``` -------------------------------- ### useSelector: Selecting Store Values Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md Shows how to use useSelector to subscribe to a store and select specific values, including an example without a selector. ```tsx import { createStore, useSelector } from '@xstate/store-react'; // ... const store = createStore({ context: { count: 0 }, on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } }); const App = () => { const count = useSelector(store, (s) => s.context.count); // or without selector (returns full snapshot) const snapshot = useSelector(store); // ... }; ``` -------------------------------- ### Create and run a state machine Source: https://github.com/statelyai/xstate/blob/main/README.md Defines a toggle machine with context and transitions, then creates and starts an actor to manage its state. ```ts import { createMachine, createActor, assign } from 'xstate'; // State machine const toggleMachine = createMachine({ id: 'toggle', initial: 'inactive', context: { count: 0 }, states: { inactive: { on: { TOGGLE: { target: 'active' } } }, active: { entry: assign({ count: ({ context }) => context.count + 1 }), on: { TOGGLE: { target: 'inactive' } } } } }); // Actor (instance of the machine logic, like a store) const toggleActor = createActor(toggleMachine); toggleActor.subscribe((state) => console.log(state.value, state.context)); toggleActor.start(); // => logs 'inactive', { count: 0 } toggleActor.send({ type: 'TOGGLE' }); // => logs 'active', { count: 1 } toggleActor.send({ type: 'TOGGLE' }); // => logs 'inactive', { count: 1 } ``` -------------------------------- ### Create Store with Standard Schema Typing Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Define context, events, and emitted events using Zod schemas for type inference and runtime metadata. This example shows how to set up schemas for context, a 'rename' event, and a 'renamed' emitted event. ```typescript import { createStore } from '@xstate/store'; import { z } from 'zod'; const store = createStore({ schemas: { context: z.object({ count: z.number(), label: z.string() }), events: { rename: z.object({ label: z.string() }) }, emitted: { renamed: z.object({ label: z.string() }) } }, context: { count: 0, label: 'ready' }, on: { rename: (context, event, enq) => { enq.emit.renamed({ label: event.label }); return { ...context, label: event.label }; } } }); ``` -------------------------------- ### Implement useMachine hook Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-react/README.md Example of defining a machine and using it within a React functional component. ```tsx import { useMachine } from '@xstate/react'; import { createMachine } from 'xstate'; const toggleMachine = createMachine({ id: 'toggle', initial: 'inactive', states: { inactive: { on: { TOGGLE: 'active' } }, active: { on: { TOGGLE: 'inactive' } } } }); export const Toggler = () => { const [state, send] = useMachine(toggleMachine); return ( ); }; ``` -------------------------------- ### Enqueue Store Events with `enq.trigger` Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Transitions can now enqueue other store events using `enq.trigger`. This example demonstrates composing 'addBear' and 'addFish' events within an 'addBearAndFish' transition. ```typescript const store = createStore({ schemas: { events: { addBear: z.object({}), addFish: z.object({ amount: z.number() }), addBearAndFish: z.object({}) } }, context: { bears: 0, fishes: 0 }, on: { addBear: (context) => ({ ...context, bears: context.bears + 1 }), addFish: (context, event) => ({ ...context, fishes: context.fishes + event.amount }), addBearAndFish: (context, _event, enq) => { enq.trigger.addBear(); enq.trigger.addFish({ amount: 1 }); return context; } } }); ``` -------------------------------- ### Infer Types with `fromStore` and Schemas Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Use `fromStore` to create store logic while inferring context, event, and emitted-event types from schema definitions. This example defines an 'increased' emitted event schema. ```typescript import { fromStore } from '@xstate/store'; import { z } from 'zod'; const logic = fromStore({ context: (initialCount: number) => ({ count: initialCount }), schemas: { emitted: { increased: z.object({ by: z.number() }) } }, on: { inc: (context, event: { by: number }, enq) => { enq.emit.increased({ by: event.by }); return { count: context.count + event.by }; } } }); ``` -------------------------------- ### Using useSelector with a custom selector and no selector Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-vue/README.md Illustrates how to use the useSelector composable to select a specific value from the store's context or to get the entire store snapshot. This is useful for fine-grained subscriptions or when the full state is needed. ```vue ``` -------------------------------- ### Using injectStore with a Selector Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-angular/README.md Creates an Angular signal subscribed to a store, selecting a specific value from the store's snapshot using a provided selector function. This example shows selecting the 'count' property. ```typescript import { Component } from '@angular/core'; import { createStore, injectStore } from '@xstate/store-angular'; // ... const store = createStore({ context: { count: 0 }, on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } }); @Component({ selector: 'app-counter', template: `
{{ count() }}
` }) export class CounterComponent { count = injectStore(store, (s) => s.context.count); // or without selector (returns full snapshot) snapshot = injectStore(store); } ``` -------------------------------- ### GET /workflows/:id Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md Retrieves the current state of a specific workflow instance. ```APIDOC ## GET /workflows/:id ### Description Gets the current state of a workflow instance. ### Method GET ### Endpoint /workflows/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the workflow instance. ### Response #### Success Response (200) - **workflowId** (string) - The ID of the workflow instance. - **state** (object) - The current state of the workflow instance. #### Response Example ```json { "workflowId": "7ky252", "state": {} } ``` ``` -------------------------------- ### GET /workflows/:id Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-credit-check-api/README.md Retrieves the current state of a specific workflow instance. ```APIDOC ## GET /workflows/:id ### Description Gets the current state of a workflow instance. ### Method GET ### Endpoint /workflows/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the workflow instance ### Response #### Success Response (200) - Returns the current state object of the workflow ``` -------------------------------- ### Create and use a store with @xstate/store Source: https://github.com/statelyai/xstate/blob/main/README.md Defines a store with initial context and event handlers, then demonstrates subscribing to changes and sending events. ```ts import { createStore } from '@xstate/store'; const donutStore = createStore({ context: { donuts: 0, favoriteFlavor: 'chocolate' }, on: { addDonut: (context) => ({ ...context, donuts: context.donuts + 1 }), changeFlavor: (context, event: { flavor: string }) => ({ ...context, favoriteFlavor: event.flavor }), eatAllDonuts: (context) => ({ ...context, donuts: 0 }) } }); donutStore.subscribe((snapshot) => { console.log(snapshot.context); }); donutStore.send({ type: 'addDonut' }); // => { donuts: 1, favoriteFlavor: 'chocolate' } donutStore.send({ type: 'changeFlavor', flavor: 'strawberry' }); // => { donuts: 1, favoriteFlavor: 'strawberry' } ``` -------------------------------- ### Get Workflow State Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md Endpoint to retrieve the current state of an existing workflow instance. ```bash curl -X GET http://localhost:4242/workflows/:id ``` -------------------------------- ### Create Workflow Instance Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md Endpoint to initialize a new workflow instance. ```bash curl -X POST http://localhost:4242/workflows ``` -------------------------------- ### Scaffold a new Vite project Source: https://github.com/statelyai/xstate/blob/main/examples/readme.md Initialize a new project using the Vite CLI with a React TypeScript template. ```bash pnpm create vite@latest my-example-react --template react-ts cd my-example-react ``` -------------------------------- ### inspect() Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md Initializes the XState inspector to monitor machine events and transitions. ```APIDOC ## inspect(options) ### Description Initializes the inspection tool. This should be called at the beginning of your project before any other code is executed. ### Parameters #### Request Body - **url** (string) - Optional - The endpoint that the Inspector sends events to. Default: https://stately.ai/viz?inspect - **iframe** (boolean) - Optional - If set to false, opens the inspector in a new window instead of an iframe. - **devTools** (boolean) - Optional - Allows custom implementation for lifecycle hooks. - **serialize** (function) - Optional - A custom serializer for messages sent to the URL endpoint, useful for sanitizing sensitive data. - **targetWindow** (Window) - Optional - Provide a pre-existing window location to be used instead of opening a new window. ``` -------------------------------- ### Initialize Inspector with Options Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md Import and initialize the inspect function, optionally configuring it to open in a new tab instead of an iframe. ```javascript import { inspect } from '@xstate/inspect'; inspect({ // options // url: 'https://stately.ai/viz?inspect', // (default) iframe: false // open in new window }); ``` -------------------------------- ### useActorRef(logic, options?) Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md A SolidJS hook that returns the actorRef created from the logic with the options, if specified. It starts the actor and runs it for the lifetime of the component. ```APIDOC ## useActorRef(logic, options?) ### Description A SolidJS hook that returns the `actorRef` created from the `logic` with the `options`, if specified. It starts the actor and runs it for the lifetime of the component. This is similar to `useActor`. `createService` returns a static reference (to just the interpreted logic) which will not rerender when its snapshot changes. ### Arguments - `logic` - The XState machine or actor logic. - `options` (optional) - [Actor options](https://xstate.js.org/docs/guides/interpretation.html#options) ### Returns The created `actorRef`. ### Request Example ```javascript import { useActorRef } from '@xstate/solid'; import { someMachine } from '../path/to/someMachine'; const App = () => { const actorRef = useActorRef(someMachine); // ... }; // With options: const AppWithOptions = () => { const service = useActorRef(someMachine, { input: { /* ... */ } }); // ... }; ``` ``` -------------------------------- ### Empty Object Schemas for Events without Payload Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md Provides an example of using empty object schemas (`z.object({})`) for events and emitted events that do not have any payload data. ```typescript schemas: { events: { reset: z.object({}) }, emitted: { reset: z.object({}) } } ``` -------------------------------- ### Creating Reactive Store Selections with `store.select` Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Demonstrates how to create reactive selections from store context using `store.select`. Subscribing to these selections allows for observing changes in specific parts of the store's state. ```typescript import { createStore } from '@xstate/store'; const store = createStore({ context: { count: 0 }, on: { inc: (context) => ({ count: context.count + 1 }) } }); const count = store.select((context) => context.count); const isEven = store.select((context) => context.count % 2 === 0); count.subscribe((value) => { console.log(value); }); store.trigger.inc(); ``` -------------------------------- ### useActor(logic, options?) Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md A SolidJS hook that interprets the given logic and starts an actor that runs for the lifetime of the component. It returns a tuple of [snapshot, send, actorRef]. ```APIDOC ## useActor(logic, options?) ### Description A SolidJS hook that interprets the given `logic` and starts an actor that runs for the lifetime of the component. ### Arguments - `logic` - The XState machine or actor logic. - `options` (optional) - Actor options. ### Returns A tuple of `[snapshot, send, actorRef]`: - `snapshot` - Represents the current snapshot of the logic. This is a read-only value that is tracked by SolidJS for granular reactivity. - `send` - A function that sends events to the running service. - `actorRef` - The created service. ### Request Example ```javascript import { useActor } from '@xstate/solid'; import { createMachine } from 'xstate'; const toggleMachine = createMachine({ id: 'toggle', initial: 'inactive', states: { inactive: { on: { TOGGLE: 'active' } }, active: { on: { TOGGLE: 'inactive' } } } }); export const Toggler = () => { const [snapshot, send] = useActor(toggleMachine); return ( ); }; ``` ``` -------------------------------- ### useAtom: Subscribing to Atoms Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md Demonstrates creating an atom and using the useAtom hook to subscribe to its value and update it. ```tsx import { createAtom, useAtom } from '@xstate/store-react'; // ... const countAtom = createAtom(0); const App = () => { const count = useAtom(countAtom); return ; }; ``` -------------------------------- ### Update Solid Store Import Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Migrate from '@xstate/store/solid' to '@xstate/store-solid' for SolidJS-specific imports. ```diff - import { useSelector } from '@xstate/store/solid'; + import { useSelector } from '@xstate/store-solid'; ``` -------------------------------- ### Creating Reusable Store Logic with `createStoreLogic` Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Shows how to define reusable store logic, including context, selectors, and event handlers, using `createStoreLogic`. This logic can then be used to create multiple stores with shared definitions. ```typescript import { createStoreLogic } from '@xstate/store'; const counterLogic = createStoreLogic({ context: (input: { initialCount: number }) => ({ count: input.initialCount }), selectors: { count: (context) => context.count, doubled: (context) => context.count * 2 }, on: { inc: (context) => ({ count: context.count + 1 }) } }); const store = counterLogic.createStore({ initialCount: 2 }); store.selectors.count.get(); // 2 store.selectors.doubled.get(); // 4 ``` -------------------------------- ### Enable Runtime Schema Validation Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Opt into runtime validation for event payloads, context, and emitted events by using `validateSchemas()` from `@xstate/store/validate`. This example demonstrates adding validation to a store with an 'increment' event. ```typescript import { validateSchemas } from '@xstate/store/validate'; const store = createStore({ schemas: { events: { increment: z.object({ by: z.number() }) } }, context: { count: 0 }, on: { increment: (context, event) => ({ count: context.count + event.by }) } }).with(validateSchemas()); ``` -------------------------------- ### POST /workflows Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-credit-check-api/README.md Creates a new workflow instance in the system. ```APIDOC ## POST /workflows ### Description Creates a new workflow instance. ### Method POST ### Endpoint /workflows ### Response #### Success Response (201) - **message** (string) - Success message - **workflowId** (string) - The unique identifier for the created workflow #### Response Example { "message": "New workflow created successfully", "workflowId": "uzkjyy" } ``` -------------------------------- ### Matching States with useActor Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md Demonstrates how to use the `snapshot.matches()` method with SolidJS's Switch and Match components for handling hierarchical and parallel states. ```APIDOC ## Matching States When using [hierarchical](https://xstate.js.org/docs/guides/hierarchical.html) and [parallel](https://xstate.js.org/docs/guides/parallel.html) machines, the state values will be objects, not strings. In this case, it is best to use `state.matches(...)`. The SolidJS [Switch and Match Components]() are ideal for this use case: ### Request Example ```jsx import { useActor } from '@xstate/solid'; import { Switch, Match } from 'solid-js'; const Loader = () => { const [snapshot, send] = useActor(/* ... */); return (
); }; ``` ``` -------------------------------- ### Optional Handlers for Schema-Declared Events Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md When events are declared via `schemas.events`, their corresponding handlers in the `on` object are optional. This example shows an 'inc' event with a handler and a 'reset' event without one, demonstrating that 'reset' becomes a no-op. ```typescript import { createStore } from '@xstate/store'; import { z } from 'zod'; const store = createStore({ schemas: { events: { inc: z.object({ by: z.number() }), reset: z.object({}) } }, context: { count: 0 }, on: { inc: (context, event) => ({ count: context.count + event.by }) } }); store.trigger.reset(); // no-op ``` -------------------------------- ### Initialize XState Machine as Actor Source: https://github.com/statelyai/xstate/blob/main/examples/workflow-media-scanner/README.md Create an actor from a machine definition. This is the entry point for interacting with the state machine. ```typescript const mediaScannerActor = createActor(mediaScannerMachine); ``` -------------------------------- ### Load @xstate/svelte via CDN Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-svelte/README.md Include the library via a script tag to access the XStateSvelte global variable. ```html ``` -------------------------------- ### Using Immer with XState Store Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md Demonstrates how to use Immer's `produce` function within XState Store transition functions for immutable updates. Imports `produce` from 'immer' or `create` from 'mutative'. ```typescript import { createStore } from '@xstate/store'; import { produce } from 'immer'; // or { create } from 'mutative' const donutStore = createStore({ context: { donuts: 0, favoriteFlavor: 'chocolate' }, on: { addDonut: (context) => produce(context, (draft) => { draft.donuts++; }), changeFlavor: (context, event: { flavor: string }) => produce(context, (draft) => { draft.favoriteFlavor = event.flavor; }), eatAllDonuts: (context) => produce(context, (draft) => { draft.donuts = 0; }) } }); ``` -------------------------------- ### POST /workflows Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md Creates a new workflow instance. ```APIDOC ## POST /workflows ### Description Creates a new workflow instance. ### Method POST ### Endpoint /workflows ### Request Example ```json {} ``` ### Response #### Success Response (200) - **workflowId** (string) - The ID of the newly created workflow instance. #### Response Example ```json { "workflowId": "7ky252" } ``` ``` -------------------------------- ### Include @xstate/vue via CDN Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-vue/README.md Include the package via a CDN for direct use in HTML. ```html ``` -------------------------------- ### Implement a Hierarchical State Machine Source: https://github.com/statelyai/xstate/blob/main/README.md Demonstrates nesting states within a parent state, where the 'red' state contains its own sub-machine. ```javascript import { createMachine, createActor } from 'xstate'; const pedestrianStates = { initial: 'walk', states: { walk: { on: { PED_TIMER: 'wait' } }, wait: { on: { PED_TIMER: 'stop' } }, stop: {} } }; const lightMachine = createMachine({ id: 'light', initial: 'green', states: { green: { on: { TIMER: 'yellow' } }, yellow: { on: { TIMER: 'red' } }, red: { on: { TIMER: 'green' }, ...pedestrianStates } } }); const actor = createActor(lightMachine); actor.subscribe((state) => { console.log(state.value); }); actor.start(); // logs 'green' actor.send({ type: 'TIMER' }); // logs 'yellow' actor.send({ type: 'TIMER' }); // logs { red: 'walk' } actor.send({ type: 'PED_TIMER' }); // logs { red: 'wait' } ``` -------------------------------- ### Implement a Finite State Machine Source: https://github.com/statelyai/xstate/blob/main/README.md Defines a basic machine with three states and transitions triggered by a TIMER event. ```javascript import { createMachine, createActor } from 'xstate'; const lightMachine = createMachine({ id: 'light', initial: 'green', states: { green: { on: { TIMER: 'yellow' } }, yellow: { on: { TIMER: 'red' } }, red: { on: { TIMER: 'green' } } } }); const actor = createActor(lightMachine); actor.subscribe((state) => { console.log(state.value); }); actor.start(); // logs 'green' actor.send({ type: 'TIMER' }); // logs 'yellow' ``` -------------------------------- ### Replace createStoreWithProducer with createStore and Immer Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Replace createStoreWithProducer with createStore and use Immer's produce within transition handlers. The producer function should now return the draft state. ```diff - import { createStoreWithProducer } from '@xstate/store'; + import { createStore } from '@xstate/store'; import { produce } from 'immer'; - const store = createStoreWithProducer(produce, { + const store = createStore({ context: { count: 0 }, on: { - inc: (context) => { - context.count++; - } + inc: (context) => + produce(context, (draft) => { + draft.count++; + }) } }); ``` -------------------------------- ### Create and Use a Store Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md Defines a store with context and event handlers, subscribes to state changes, and triggers events using the `trigger` API. ```typescript import { createStore } from '@xstate/store'; export const donutStore = createStore({ context: { donuts: 0, favoriteFlavor: 'chocolate' }, on: { addDonut: (context) => ({ ...context, donuts: context.donuts + 1 }), changeFlavor: (context, event: { flavor: string }) => ({ ...context, favoriteFlavor: event.flavor }), eatAllDonuts: (context) => ({ ...context, donuts: 0 }) } }); donutStore.subscribe((snapshot) => { console.log(snapshot.context); }); // Equivalent to // donutStore.send({ type: 'addDonut' }); donutStore.trigger.addDonut(); // => { donuts: 1, favoriteFlavor: 'chocolate' } // donutStore.send({ // type: 'changeFlavor', // flavor: 'strawberry' // Strongly-typed! // }); donutStore.trigger.changeFlavor({ flavor: 'strawberry' }); // => { donuts: 1, favoriteFlavor: 'strawberry' } ``` -------------------------------- ### Include @xstate/inspect via CDN Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md Include the inspector script via a CDN for global access. ```html ``` -------------------------------- ### createWindowReceiver() Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md Creates a receiver to listen to messages sent by the inspector, useful for custom logging or external tools. ```APIDOC ## createWindowReceiver(options) ### Description Creates a receiver that subscribes to messages from @xstate/inspector, allowing you to handle events like service registration, state changes, and event processing. ### Response - **event** (object) - The event object containing type and payload information for service.register, service.stop, service.event, or service.state. ``` -------------------------------- ### Implement Immer with XState machine Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-immer/README.md Use assign and createUpdater to perform immutable context updates within a machine definition. ```javascript import { createMachine, interpret } from 'xstate'; import { assign, createUpdater } from '@xstate/immer'; const levelUpdater = createUpdater('UPDATE_LEVEL', (ctx, { input }) => { ctx.level = input; }); const toggleMachine = createMachine({ id: 'toggle', context: { count: 0, level: 0 }, initial: 'inactive', states: { inactive: { on: { TOGGLE: { target: 'active', // Immutably update context the same "mutable" // way as you would do with Immer! actions: assign((ctx) => ctx.count++) } } }, active: { on: { TOGGLE: { target: 'inactive' }, // Use the updater for more convenience: [levelUpdater.type]: { actions: levelUpdater.action } } } } }); const toggleService = interpret(toggleMachine) .onTransition((state) => { console.log(state.context); }) .start(); toggleService.send({ type: 'TOGGLE' }); // { count: 1, level: 0 } toggleService.send(levelUpdater.update(9)); // { count: 1, level: 9 } toggleService.send({ type: 'TOGGLE' }); // { count: 2, level: 9 } toggleService.send(levelUpdater.update(-100)); // Notice how the level is not updated in 'inactive' state: // { count: 2, level: 9 } ``` -------------------------------- ### Update React Store Import Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Migrate from '@xstate/store/react' to '@xstate/store-react' for React-specific imports. ```diff - import { useSelector } from '@xstate/store/react'; + import { useSelector } from '@xstate/store-react'; ``` -------------------------------- ### Update createStore to use config object Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Migrate from the deprecated two-argument createStore(context, transitions) API to the config object form. ```diff - const store = createStore( - { count: 0 }, - { - inc: (context) => ({ count: context.count + 1 }) - } - ); + const store = createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } + }); ``` -------------------------------- ### Enable DevTools for Interpreted Machines Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md Enable the devTools option when interpreting machines to allow visualization. ```javascript import { interpret } from 'xstate'; import { inspect } from '@xstate/inspect'; // ... const service = interpret(someMachine, { devTools: true }); service.start(); ``` -------------------------------- ### useStore: Component-Scoped Store Instance Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md Illustrates creating a store instance that is scoped to a specific React component using the useStore hook. ```tsx import { useStore, useSelector } from '@xstate/store-react'; // ... const App = () => { const store = useStore({ context: { count: 0 }, on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } }); const count = useSelector(store, (s) => s.context.count); // ... }; ``` -------------------------------- ### Create History State Machine in JavaScript Source: https://github.com/statelyai/xstate/blob/main/packages/core/README.md Demonstrates a payment state machine using a history state to remember the last active payment method (cash or check). Use history states to preserve context within a region. ```javascript import { createMachine, createActor } from 'xstate'; const paymentMachine = createMachine({ id: 'payment', initial: 'method', states: { method: { initial: 'cash', states: { cash: { on: { SWITCH_CHECK: 'check' } }, check: { on: { SWITCH_CASH: 'cash' } }, hist: { type: 'history' } }, on: { NEXT: 'review' } }, review: { on: { PREVIOUS: 'method.hist' } } } }); const actor = createActor(paymentMachine); actor.subscribe((state) => { console.log(state.value); }); actor.start(); // logs { // value: { method: 'cash' }, // } actor.send({ type: 'SWITCH_CHECK' }); // logs { // value: { method: 'check' }, // } actor.send({ type: 'NEXT' }); // logs { // value: 'review', // } actor.send({ type: 'PREVIOUS' }); // logs { // value: { method: 'check' }, // } ``` -------------------------------- ### Using useSelector with XState Store in Svelte Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-svelte/README.md Illustrates how to use the `useSelector` hook from @xstate/store-svelte to subscribe to an XState store and select specific values. It shows usage with and without a selector function. ```svelte
{$count}
``` -------------------------------- ### Match states with Switch and Match Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md Use SolidJS Switch and Match components to handle hierarchical or parallel state values. ```jsx const Loader = () => { const [snapshot, send] = useActor(/* ... */); return (
); }; ``` -------------------------------- ### useStore(definition) Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md Creates a store instance that is scoped to a specific component. This hook ensures that the store instance is stable across re-renders of the component. ```APIDOC ## useStore(definition) ### Description Creates a store instance that is scoped to the component where it is used. This hook returns a stable store instance across re-renders, ensuring consistent behavior. ### Arguments - `definition` - An object that defines the store's configuration, including its initial context and event handlers. ### Returns A stable store instance that can be used within the component. ``` -------------------------------- ### Add Machine ID in Configuration Source: https://github.com/statelyai/xstate/blob/main/migration.md It is recommended to add an `id` property to the root state node (machine) configuration. This may become a strict requirement in future versions. ```javascript const machine = createMachine({ id: 'light', // add this property! initial: 'green', states: { /* ... */ } }); ``` -------------------------------- ### Use useActor hook Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md Interpret a machine and manage its lifecycle within a SolidJS component. ```js import { useActor } from '@xstate/solid'; import { createMachine } from 'xstate'; const toggleMachine = createMachine({ id: 'toggle', initial: 'inactive', states: { inactive: { on: { TOGGLE: 'active' } }, active: { on: { TOGGLE: 'inactive' } } } }); export const Toggler = () => { const [snapshot, send] = useActor(toggleMachine); return ( ); }; ``` -------------------------------- ### createStoreHook: Custom Store Hook Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md Shows how to create a custom hook using createStoreHook that returns both the selected value and the store instance. ```tsx import { createStoreHook } from '@xstate/store-react'; // ... const useCountStore = createStoreHook({ context: { count: 0 }, on: { inc: (ctx, e: { by: number }) => ({ ...ctx, count: ctx.count + e.by }) } }); const App = () => { const [count, store] = useCountStore((s) => s.context.count); return ; }; ``` -------------------------------- ### Persisted and Rehydrated State with useActor Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md Shows how to persist and rehydrate state using the `options.snapshot` argument in the `useActor` hook. ```APIDOC ## Persisted and Rehydrated State You can persist and rehydrate state with `useActor(...)` via `options.snapshot`: ### Request Example ```javascript // ... // Get the persisted state config object from somewhere, e.g. localStorage const persistedSnapshot = JSON.parse(localStorage.getItem('some-persisted-state-key')) || someMachine.initialState; const App = () => { const [snapshot, send] = useActor(someMachine, { snapshot: persistedSnapshot }); // snapshot will rehydrate the provided persisted snapshot, it won't be the machine's initial snapshot return (/* ... */) } ``` ``` -------------------------------- ### String Transition Targets Still Work Source: https://github.com/statelyai/xstate/blob/main/migration.md String targets for transitions are still supported in v4. ```javascript const machine = createMachine({ // ... states: { green: { on: { // ✅ still works in v4 TIMER: 'yellow' } } } }); ``` -------------------------------- ### Configure MongoDB Connection String Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-credit-check-api/README.md Update this line with your MongoDB connection URI. Ensure the database is named 'creditCheck'. ```typescript const uri = "/creditCheck"; ``` -------------------------------- ### Consolidating Store Inspection Events Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Shows the change in `store.inspect(...)` where multiple event types (`@xstate.actor`, `@xstate.event`, `@xstate.snapshot`) are replaced by a single `@xstate.transition` event. ```diff store.inspect((inspectionEvent) => { - // '@xstate.actor' | '@xstate.event' | '@xstate.snapshot' + // '@xstate.transition' + inspectionEvent.event; + inspectionEvent.snapshot; }); ``` -------------------------------- ### Workflow Creation Response Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md Expected JSON response structure after creating a workflow. ```json { "workflowId": "7ky252" } ``` -------------------------------- ### Update undoRedo to use extension form Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md Replace the deprecated config-wrapping form of undoRedo(...) with the extension form using .with(undoRedo()). ```diff - const store = createStore( - undoRedo({ - context: { count: 0 }, - on: { - inc: (context) => ({ count: context.count + 1 }) - } - }) - ); + const store = createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } + }).with(undoRedo()); ``` -------------------------------- ### Usage with SolidJS: `useSelector` Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md Integrate with SolidJS using `useSelector` from `@xstate/store-solid` to select state and `store.send` to dispatch events. ```tsx import { donutStore } from './donutStore.ts'; import { useSelector } from '@xstate/store-solid'; function DonutCounter() { const donutCount = useSelector(donutStore, (state) => state.context.donuts); return (
); } ``` -------------------------------- ### Replace MongoDB Connection String Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-persisted-state/README.md Replace this placeholder with your actual MongoDB connection string or load it from an environment variable. ```typescript const uri = ''; ```