### Install and Start the Express Workflow Engine
Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md
Commands to install dependencies and start the development server.
```bash
pnpm install
pnpm start
```
--------------------------------
### npm i xstate @xstate/svelte - install packages
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-svelte/README.md
Install the required packages via npm. This is the first step in the quick start guide.
```bash
npm i xstate @xstate/svelte
```
--------------------------------
### Install xstate and @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/react
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-react/README.md
Install the required dependencies using npm.
```bash
npm i xstate @xstate/react
```
--------------------------------
### Install @xstate/store-preact with npm
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-preact/README.md
Install the package using npm.
```bash
npm install @xstate/store-preact
```
--------------------------------
### Run TodoMVC locally with pnpm
Source: https://github.com/statelyai/xstate/blob/main/examples/todomvc-react/readme.md
Commands to navigate to the project directory, install dependencies, and start the development server.
```shell
cd examples/todomvc-react
pnpm install
pnpm run dev
```
--------------------------------
### Create and use a store with createStore
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md
Quick start example: create a store with context and event handlers, subscribe to snapshot changes, and trigger events. The trigger methods are strongly typed and equivalent to send calls.
```ts
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' }
```
--------------------------------
### Install @xstate/store-vue with npm
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-vue/README.md
Installation command for the Vue adapter package.
```bash
npm install @xstate/store-vue
```
--------------------------------
### Install dependencies
Source: https://github.com/statelyai/xstate/blob/main/examples/trivia-game-example/README.md
Run this command to install all required packages for the project.
```bash
pnpm install
```
--------------------------------
### 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-svelte
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-svelte/README.md
Install the package using npm.
```bash
npm install @xstate/store-svelte
```
--------------------------------
### Install @xstate/store-angular
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-angular/README.md
Install the Angular adapter package using npm.
```bash
npm install @xstate/store-angular
```
--------------------------------
### Install @xstate/store
Source: https://github.com/statelyai/xstate/blob/main/README.md
Install the @xstate/store package via npm.
```bash
npm install @xstate/store
```
--------------------------------
### 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 on http://localhost:5173.
```bash
yarn dev
```
--------------------------------
### Install XState with npm
Source: https://github.com/statelyai/xstate/blob/main/packages/core/README.md
Install the xstate package using npm.
```bash
npm install xstate
```
--------------------------------
### Quickstart: Vue component with createStore and useSelector
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-vue/README.md
Vue component showing how to create a store and select a value using useSelector, with a button to send events.
```vue
```
--------------------------------
### Install XState dependencies
Source: https://github.com/statelyai/xstate/blob/main/examples/readme.md
Install the core xstate library and the required framework-specific package.
```bash
pnpm install xstate @xstate/react
```
--------------------------------
### useSelector API example in Solid
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-solid/README.md
Creates a signal that subscribes to a store and returns a selected value. The accessor reconciles updates made during component setup before its subscription starts. Works with the store's readable snapshot interface; store-specific code can still use store.getSnapshot() directly.
```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
{count()}
;
};
```
--------------------------------
### Quickstart: createStore and useSelector in Preact
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-preact/README.md
Shows how to create a store with createStore and use useSelector to subscribe to a selected value, triggering re-renders on change.
```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 (
);
};
```
--------------------------------
### useSelector example with optional selector
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-vue/README.md
Vue component demonstrating use of useSelector with a selector, and without a selector to get the full snapshot.
```vue
{{ count }}
```
--------------------------------
### Install @xstate/store-solid with npm
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
```
--------------------------------
### Quickstart: createStore and useSelector in Solid
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-solid/README.md
Shows a minimal Solid component using createStore and useSelector to subscribe to a store and render a count with an increment button.
```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 (
);
};
```
--------------------------------
### Quickstart: createStore and useSelector in Svelte
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-svelte/README.md
Shows how to create an XState store and use useSelector to subscribe to a selected value in a Svelte component.
```svelte
```
--------------------------------
### Install @xstate/store-react with npm
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md
Install the React adapter for @xstate/store using npm.
```bash
npm install @xstate/store-react
```
--------------------------------
### Install immer, xstate, and @xstate/immer
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-immer/README.md
Install the required packages. Note that immer is a peer-dependency and does not need to be imported.
```bash
npm install immer xstate @xstate/immer
```
--------------------------------
### Install xstate and @xstate/vue via npm
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-vue/README.md
Install the required packages for using XState with Vue. Run this command in your project directory.
```bash
npm i xstate @xstate/vue
```
--------------------------------
### Install @xstate/inspect with npm
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md
Installs the @xstate/inspect package using npm. The yarn alternative is commented out.
```bash
npm install @xstate/inspect
# or yarn add @xstate/inspect
```
--------------------------------
### Run the sample with ts-node
Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-persisted-state/README.md
Run this command in the terminal to start the project. It uses ts-node with ES modules to execute main.ts.
```bash
yarn ts-node --esm ./main.ts
```
--------------------------------
### Use useMachine hook
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md
Example of interpreting an existing machine.
```js
// existing machine
const [snapshot, send] = useMachine(machine);
```
--------------------------------
### useSelector(store, selector, compare?)
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-solid/README.md
Creates a signal that subscribes to a store and returns a selected value. The accessor reconciles updates made during component setup before its subscription starts.
```APIDOC
## useSelector(store, selector, compare?)
### Description
Creates a signal that subscribes to a store and returns a selected value. The accessor reconciles updates made during component setup before its subscription starts.
### Arguments
- **store** - Store created with `createStore()`
- **selector** - Function to select a value from snapshot
- **compare?** - Equality function (default: `===`)
### Returns
Read-only signal of the selected value
### Example
```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
{count()}
;
};
```
```
--------------------------------
### Quickstart: createStore and useSelector
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md
Basic usage of createStore and useSelector to subscribe to a store and render 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 (
);
};
```
--------------------------------
### Quickstart: Counter component with injectStore
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-angular/README.md
A complete Angular component using createStore and injectStore to create a signal for the count value, with a button that sends an 'inc' event.
```ts
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);
}
```
--------------------------------
### Install @xstate/store with npm
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md
Install the @xstate/store package using npm. The commented lines show equivalent commands for yarn and pnpm.
```bash
# yarn add @xstate/store
# pnpm add @xstate/store
npm install @xstate/store
```
--------------------------------
### Create and run a toggle machine with XState
Source: https://github.com/statelyai/xstate/blob/main/packages/core/README.md
This TypeScript example creates a toggle state machine with a count context, creates an actor, and demonstrates sending TOGGLE events. The output logs the state value and context after each event.
```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 }
```
--------------------------------
### useSelector with and without selector
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-svelte/README.md
Demonstrates using useSelector with a selector to get a specific value, and without a selector to get the full snapshot.
```svelte
{$count}
```
--------------------------------
### createSourceAtom with media query listener
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md
Use createSourceAtom to wrap an external value, here a media query, with getSnapshot and subscribe. Direct and derived subscribers share one listener; cleanup runs synchronously when the last consumer leaves. Plain reads do not start listeners, and resubscribing reconnects and refreshes the snapshot.
```ts
import { createAtom, createSourceAtom } from '@xstate/store';
const media = window.matchMedia('(prefers-color-scheme: dark)');
const isDark = createSourceAtom({
getSnapshot: () => media.matches,
subscribe: (notify) => {
media.addEventListener('change', notify);
return () => media.removeEventListener('change', notify);
}
});
const theme = createAtom(() => (isDark.get() ? 'dark' : 'light'));
const subscription = theme.subscribe(console.log);
subscription.unsubscribe(); // Removes the media query listener.
```
--------------------------------
### useSelector with and without selector
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-preact/README.md
Demonstrates using useSelector with a selector to get a specific value, and without a selector to get the full snapshot.
```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);
// or without selector (returns full snapshot)
const snapshot = useSelector(store);
// ...
};
```
--------------------------------
### Use useActor hook
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-solid/README.md
Example of using the useActor hook to interpret a machine and interact with it in 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 (
);
};
```
--------------------------------
### GET /workflows/:id
Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-credit-check-api/README.md
Gets the current state of a 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 workflow ID
### Response
No response schema described.
```
--------------------------------
### Use assign() and createUpdater() with XState
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-immer/README.md
Imports the utilities and defines a machine with context updates. The assign() action uses Immer's mutable style, and createUpdater() defines an event type and action. The example shows sending events and the resulting context.
```js
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 }
```
--------------------------------
### GET /workflows/:id
Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md
Gets the current state of a 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.
### Request Example
```bash
curl -X GET http://localhost:4242/workflows/:id
```
```
--------------------------------
### useMachine toggle example in Svelte
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-svelte/README.md
A complete Svelte component that defines a toggle machine and uses useMachine to manage its state, with a button to toggle.
```svelte
```
--------------------------------
### Use Immer's produce inside XState Store transitions
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md
Use `produce(...)` from Immer (or `create` from Mutative) inside transition functions to handle immutable updates. The example defines a store with `addDonut`, `changeFlavor`, and `eatAllDonuts` transitions.
```ts
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;
})
}
});
```
--------------------------------
### injectStore with selector and without selector
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-angular/README.md
Shows two usages of injectStore: with a selector to get a specific value, and without a selector to get the full snapshot. The component template displays the selected count.
```ts
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);
}
```
--------------------------------
### Emit events from transitions with enqueue.emit and schemas.emitted
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md
Declare emitted events in `schemas.emitted` and use `enqueue.emit` to emit them during a transition. Listen for these events with `store.on` to react to them, as shown in the example.
```ts
import { createStore } from '@xstate/store';
import { z } from 'zod';
const store = createStore({
schemas: {
emitted: {
increased: z.object({
by: z.number()
})
}
},
context: { count: 0 },
on: {
inc: (context, event: { by: number }, enqueue) => {
enqueue.emit.increased({ by: event.by });
return {
...context,
count: context.count + event.by
};
}
}
});
// Listen for emitted events
store.on('increased', (event) => {
console.log(`Count increased by ${event.by}`);
});
```
--------------------------------
### Send START_SCAN event to actor (index.ts)
Source: https://github.com/statelyai/xstate/blob/main/examples/workflow-media-scanner/README.md
Sends the START_SCAN event to trigger the workflow. This event is required to start the scanning process.
```typescript
// index.ts
// ...
mediaScannerActor.send({ type: 'START_SCAN' });
```
--------------------------------
### Create a store with inferred context and event types
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md
Use `createStore` from `@xstate/store` to define a store with an initial context and transition functions. The context type is inferred from the initial context object, and event types are inferred from the event payloads in the transition functions. `getSnapshot()` returns an explicit snapshot, while `get()` is for tracked/reactive reads.
```TypeScript
import { createStore } from '@xstate/store';
const donutStore = createStore({
// Context inferred as:
// {
// donuts: number;
// favoriteFlavor: string;
// }
context: {
donuts: 0,
favoriteFlavor: 'chocolate'
},
on: {
// Event inferred as:
// {
// type: 'changeFlavor';
// flavor: string;
// }
changeFlavor: (context, event: { flavor: string }) => {
context.favoriteFlavor = event.flavor;
}
}
});
donutStore.getSnapshot().context.favoriteFlavor; // string
donutStore.get().context.favoriteFlavor; // same snapshot, readable/tracked read
donutStore.send({
type: 'changeFlavor', // Strongly-typed from transition key
flavor: 'strawberry' // Strongly-typed from { flavor: string }
});
```
--------------------------------
### History states example with createMachine and createActor
Source: https://github.com/statelyai/xstate/blob/main/packages/core/README.md
Defines a payment machine with a history state 'hist' inside the 'method' state. The actor logs state.value after each transition, demonstrating that sending PREVIOUS from 'review' returns to the last visited sub-state ('check' in this case).
```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' },
// }
```
--------------------------------
### Add a custom serializer to @xstate/inspector events and transitions messages
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md
Examples of custom serialize functions: one removes sensitive 'credentials' objects, another logs when the 'ready' key is serialized.
```typescript
// Remove credentials from being forwarded
inspect({
serialize: (key: string, value: any) => {
return key === 'credentials' && typeof value === 'object' ? {} : value;
}
});
// Add a custom local log
inspect({
serialize: (key: string, value: any) => {
if (key === 'ready') {
console.log('Detected ready key');
}
return value;
}
});
```
--------------------------------
### 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. 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. Returns a tuple of [snapshot, send, actorRef].
### Arguments
- **logic** - The state machine logic to interpret.
- **options** (optional) - Actor options, including `snapshot` for persisted state.
### Returns
- **snapshot** - Represents the current snapshot of the logic. Read-only value tracked by SolidJS for granular reactivity.
- **send** - A function that sends events to the running service.
- **actorRef** - The created service.
### Example
```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 (
);
};
```
### Persisted State Example
```js
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
};
```
```
--------------------------------
### sourceAtom.subscribe()
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/docs/source-atoms.md
Subscribes to changes of the source atom. The first subscription starts the external listener, and consumers share one listener per source atom instance. Returns a subscription object with an `unsubscribe()` method.
```APIDOC
## sourceAtom.subscribe()
### Description
Subscribes to changes of the source atom. The first subscription starts the external listener, and consumers share one listener per source atom instance. Returns a subscription object with an `unsubscribe()` method.
### Method
SUBSCRIBE
### Endpoint
sourceAtom.subscribe(listener)
### Parameters
- **listener** (function) - Required - Callback invoked with the new value when the snapshot changes.
### Returns
A subscription object with an `unsubscribe()` method.
### Example
```ts
const subscription = isDark.subscribe((value) => console.log(value));
// Later
subscription.unsubscribe();
```
```
--------------------------------
### Get Current Workflow State
Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md
Retrieves the current state of a workflow instance using a GET request.
```bash
curl -X GET http://localhost:4242/workflows/:id
```
--------------------------------
### Create a new workflow instance
Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-credit-check-api/README.md
Send a POST request to the /workflows endpoint to initialize a new workflow.
```bash
curl -X POST http://localhost:4242/workflows
```
--------------------------------
### Migrate Solid import from @xstate/store/solid to @xstate/store-solid
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md
Replace the removed @xstate/store/solid subpath import with the dedicated @xstate/store-solid package.
```diff
- import { useSelector } from '@xstate/store/solid';
+ import { useSelector } from '@xstate/store-solid';
```
--------------------------------
### Replace createStoreWithProducer with createStore and producer in transition
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md
Shows the migration from createStoreWithProducer(produce, config) to createStore(config) with produce called inside the transition handler.
```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++;
+ })
}
});
```
--------------------------------
### Easily log all machine events and transitions
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md
Sets up a local inspector and a receiver in the same window to log all events and transitions to the console. Note: the receiver is created with createWindowReceiver({}).
```typescript
// The URL and port of your local project (ex. Vite, Webpack, etc).
const url = 'http://127.0.0.1:5174/';
const inspector = inspect({
url,
iframe: undefined,
targetWindow: window
});
// In the same window, subscribe to messages from @xstate/inspector
createWindowReceiver({}).subscribe(console.log);
// Start your machine, and all events generated are logged to the console
interpret(machine, { devTools: true }).start({});
```
--------------------------------
### Scaffold a new Vite project
Source: https://github.com/statelyai/xstate/blob/main/examples/readme.md
Initialize a new Vite project using the react-ts template and navigate into the directory.
```bash
pnpm create vite@latest my-example-react --template react-ts
cd my-example-react
```
--------------------------------
### Create and use a donut store
Source: https://github.com/statelyai/xstate/blob/main/README.md
Creates a store with context and event handlers, subscribes to snapshot changes, and sends events to update the context. Logs the context after each event.
```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' }
```
--------------------------------
### 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. Similar to `useActor`, but returns a static reference that does not rerender on snapshot changes.
### Arguments
- **logic** - The state machine logic to interpret.
- **options** (optional) - Actor options, such as `input`.
### Returns
- **actorRef** - The created service reference.
### Example
```js
import { useActorRef } from '@xstate/solid';
import { someMachine } from '../path/to/someMachine';
const App = () => {
const actorRef = useActorRef(someMachine);
// ...
};
```
### With Options Example
```js
const App = () => {
const service = useActorRef(someMachine, {
input: { /* ... */ }
});
// ...
};
```
```
--------------------------------
### Create a New Workflow Instance
Source: https://github.com/statelyai/xstate/blob/main/examples/express-workflow/README.md
Sends a POST request to create a new workflow instance and displays the resulting workflow ID.
```bash
curl -X POST http://localhost:4242/workflows
```
```json
{
"workflowId": "7ky252"
}
```
--------------------------------
### Initialize XState machine as an actor (index.ts)
Source: https://github.com/statelyai/xstate/blob/main/examples/workflow-media-scanner/README.md
Creates an actor from the mediaScannerMachine using createActor. This is the first step to running the state machine.
```typescript
// index.ts
// ...
const mediaScannerActor = createActor(mediaScannerMachine);
```
--------------------------------
### Import and initialize inspect
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-inspect/README.md
Imports the inspect function and initializes it with the default options: iframe: false opens a new window, and the default URL points to stately.ai/viz?inspect.
```js
import { inspect } from '@xstate/inspect';
inspect({
// options
// url: 'https://stately.ai/viz?inspect', // (default)
iframe: false // open in new window
});
```
--------------------------------
### useStore(definition, options?)
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-react/README.md
Creates a store instance scoped to a component. The store instance is stable across re-renders.
```APIDOC
## useStore(definition, options?)
### Description
Creates a store instance scoped to a component. The store instance is stable across re-renders.
### Arguments
- `definition` (Object) - Required - Store configuration object, or store logic created with `createStoreLogic()` (followed by its `input`)
- `options?` (Object) - Optional - Options object:
- `inspect?` (Observer or callback) - Optional - Observer or callback that receives inspection events from the store
### Returns
Store instance (stable across re-renders)
### Example
```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);
// ...
};
```
To wire up an inspector, pass the `inspect` option:
```tsx
const store = useStore(
{
context: { count: 0 },
on: {
inc: (ctx) => ({ ...ctx, count: ctx.count + 1 })
}
},
{ inspect: inspector.inspect }
);
```
```
--------------------------------
### Migrate two-argument createStore to config object form
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md
Replace the deprecated createStore(context, transitions) call with the config object form using context and on properties.
```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 })
+ }
+ });
```
--------------------------------
### useSelector(store, selector?, compare?)
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store-svelte/README.md
Creates a Svelte readable store that subscribes to an XState store and returns a selected value. It accepts a store, an optional selector function, and an optional equality function.
```APIDOC
## useSelector(store, selector?, compare?)
### Description
Creates a Svelte readable store that subscribes to an XState store and returns a selected value. The selector function can be omitted to return the full snapshot.
### Method
Function
### Signature
useSelector(store, selector?, compare?)
### Parameters
- **store** (Store) - Required - Store created with `createStore()`.
- **selector?** (Function) - Optional - Function to select a value from snapshot.
- **compare?** (Function) - Optional - Equality function (default: `===`).
### Returns
Svelte readable store
### Example
```svelte
{$count}
```
```
--------------------------------
### Return undefined from transition to make it unavailable
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md
To make a transition unavailable, return `undefined` from the transition before calling `produce(...)`. This example shows an `eatDonut` transition that returns early when `context.donuts` is 0.
```ts
on: {
eatDonut: (context) => {
if (context.donuts === 0) {
return;
}
return produce(context, (draft) => {
draft.donuts--;
});
};
}
```
--------------------------------
### Updated Transition Object Syntax
Source: https://github.com/statelyai/xstate/blob/main/migration.md
Demonstrates the required object syntax for transitions, where the target is explicitly defined.
```js
const machine = createMachine({
// ...
states: {
green: {
on: {
// ✅ will work in v4
TIMER: {
target: 'yellow',
actions: 'doSomething' // notice: array not necessary anymore!
}
}
}
}
});
```
--------------------------------
### Persist state with persist and flushStorage
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/README.md
Use the persist extension to save state after events are committed. Calling store.can or the pure store.transition method does not schedule writes. Writes preserve commit order, including events triggered synchronously by effects or subscriptions. A newer eligible event can supersede an older pending write; onDone runs for writes actually performed. Asynchronous writes execute in event order for each store. Call await flushStorage(store) to write buffered changes and wait for queued writes to finish. Synchronous storage adapters continue to write synchronously.
```ts
import { persist, flushStorage } from '@xstate/store/persist';
const savedDonutStore = donutStore.with(persist({ name: 'donuts' }));
savedDonutStore.trigger.addDonut();
await flushStorage(savedDonutStore);
```
--------------------------------
### Migrate undoRedo config-wrapping to extension form with .with()
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md
Replace the deprecated undoRedo(config) wrapping form 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());
```
--------------------------------
### Migrate React import from @xstate/store/react to @xstate/store-react
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md
Replace the removed @xstate/store/react subpath import with the dedicated @xstate/store-react package.
```diff
- import { useSelector } from '@xstate/store/react';
+ import { useSelector } from '@xstate/store-react';
```
--------------------------------
### Load @xstate/vue via CDN
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-vue/README.md
Include the @xstate/vue library from a CDN. The global variable XStateVue is then available for use.
```html
```
--------------------------------
### Create and run a parallel state machine with XState
Source: https://github.com/statelyai/xstate/blob/main/README.md
Defines a parallel state machine with four independent regions (bold, underline, italics, list) and demonstrates sending events to toggle states. The actor subscription logs the state value after each event, showing the parallel state object.
```TypeScript
import { createMachine, createActor } from 'xstate';
const wordMachine = createMachine({
id: 'word',
type: 'parallel',
states: {
bold: {
initial: 'off',
states: {
on: {
on: { TOGGLE_BOLD: 'off' }
},
off: {
on: { TOGGLE_BOLD: 'on' }
}
}
},
underline: {
initial: 'off',
states: {
on: {
on: { TOGGLE_UNDERLINE: 'off' }
},
off: {
on: { TOGGLE_UNDERLINE: 'on' }
}
}
},
italics: {
initial: 'off',
states: {
on: {
on: { TOGGLE_ITALICS: 'off' }
},
off: {
on: { TOGGLE_ITALICS: 'on' }
}
}
},
list: {
initial: 'none',
states: {
none: {
on: {
BULLETS: 'bullets',
NUMBERS: 'numbers'
}
},
bullets: {
on: {
NONE: 'none',
NUMBERS: 'numbers'
}
},
numbers: {
on: {
BULLETS: 'bullets',
NONE: 'none'
}
}
}
}
}
});
const actor = createActor(wordMachine);
actor.subscribe((state) => {
console.log(state.value);
});
actor.start();
// logs {
// bold: 'off',
// italics: 'off',
// underline: 'off',
// list: 'none'
// }
actor.send({ type: 'TOGGLE_BOLD' });
// logs {
// bold: 'on',
// italics: 'off',
// underline: 'off',
// list: 'none'
// }
actor.send({ type: 'TOGGLE_ITALICS' });
// logs {
// bold: 'on',
// italics: 'on',
// underline: 'off',
// list: 'none'
// }
```
--------------------------------
### Create reactive store selections
Source: https://github.com/statelyai/xstate/blob/main/packages/xstate-store/MIGRATION.md
Use store.select(selector) to create reactive selections from the store context.
```ts
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();
```
--------------------------------
### Batch results and assign multiple context properties (fileHandlers.ts and mediaScannerMachine.ts)
Source: https://github.com/statelyai/xstate/blob/main/examples/workflow-media-scanner/README.md
Shows the return of dirsToEvaluate and dirsToReport from fileHandlers.ts, and the corresponding assign action in mediaScannerMachine.ts that sets both properties on the actor's context.
```typescript
...
return { dirsToEvaluate, dirsToReport };
```
```typescript
actions: assign(({ event }) => {
return {
dirsToEvaluate: event.output['dirsToEvaluate'],
dirsToReport: event.output['dirsToReport']
};
});
```
--------------------------------
### Workflow creation response
Source: https://github.com/statelyai/xstate/blob/main/examples/mongodb-credit-check-api/README.md
The expected JSON response after successfully creating a workflow.
```json
{
{"message":"New workflow created successfully","workflowId":"uzkjyy"}
}
```