### Quick start example for XState Store Source: https://stately.ai/docs/xstate-store Demonstrates creating a store with context, event handlers, and emitting events. Subscribe to snapshot changes and handle emitted events. ```typescript import { createStore } from '@xstate/store'; import { z } from 'zod'; const store = createStore({ schemas: { emitted: { increased: z.object({ by: z.number(), total: z.number() }), }, }, context: { count: 0 }, on: { inc: (context, event: { by: number }, enqueue) => { const count = context.count + event.by; enqueue.emit.increased({ by: event.by, total: count }); return { count }; }, }, }); store.subscribe((snapshot) => { console.log(snapshot.context); }); store.on('increased', (event) => { console.log(`Count increased by ${event.by}`); }); store.trigger.inc({ by: 2 }); // logs { count: 2 } // logs "Count increased by 2" ``` -------------------------------- ### Install @xstate/store-solid with yarn Source: https://stately.ai/docs/xstate-store/solid Install the package using yarn. ```bash yarn add @xstate/store-solid ``` -------------------------------- ### Install @xstate/store-solid with npm Source: https://stately.ai/docs/xstate-store/solid Install the package using npm. ```bash npm install @xstate/store-solid ``` -------------------------------- ### Install @xstate/store-solid with pnpm Source: https://stately.ai/docs/xstate-store/solid Install the package using pnpm. ```bash pnpm install @xstate/store-solid ``` -------------------------------- ### Zustand Store Creation and Action Example Source: https://stately.ai/docs/xstate-store/compare-zustand A typical Zustand store setup with initial state and an action method (`inc`) to modify the state. ```javascript const useCountStore = create((set) => ({ count: 0, inc: (by: number) => set((state) => ({ count: state.count + by, })), })); ``` -------------------------------- ### Install @xstate/store-vue with npm Source: https://stately.ai/docs/xstate-store/vue Install the package using npm. ```bash npm install @xstate/store-vue ``` -------------------------------- ### Install @xstate/store-vue with pnpm Source: https://stately.ai/docs/xstate-store/vue Install the package using pnpm. ```bash pnpm install @xstate/store-vue ``` -------------------------------- ### Install @xstate/store-vue with yarn Source: https://stately.ai/docs/xstate-store/vue Install the package using yarn. ```bash yarn add @xstate/store-vue ``` -------------------------------- ### Install @xstate/store-svelte with npm Source: https://stately.ai/docs/xstate-store/svelte Install the package using npm. ```bash npm install @xstate/store-svelte ``` -------------------------------- ### Basic Undo/Redo Setup Source: https://stately.ai/docs/xstate-store/undo-redo Initializes the store with the undoRedo extension and demonstrates basic undo/redo operations. ```typescript import { createStore } from '@xstate/store'; import { undoRedo } from '@xstate/store/undo'; const store = createStore({ context: { count: 0 }, on: { inc: (context) => ({ count: context.count + 1 }), }, }).with(undoRedo()); store.trigger.inc(); // count = 1 store.trigger.inc(); // count = 2 store.trigger.undo(); // count = 1 store.trigger.redo(); // count = 2 ``` -------------------------------- ### Install @xstate/store with npm Source: https://stately.ai/docs/xstate-store Install the @xstate/store package using npm. ```bash npm install @xstate/store ``` -------------------------------- ### Vue Quick Start with XState Store Source: https://stately.ai/docs/xstate-store/vue Demonstrates creating a store with initial context and actions, and subscribing to its state using `useSelector`. ```vue ``` -------------------------------- ### Install @xstate/store with yarn Source: https://stately.ai/docs/xstate-store Install the @xstate/store package using yarn. ```bash yarn add @xstate/store ``` -------------------------------- ### Install @xstate/store-svelte with pnpm Source: https://stately.ai/docs/xstate-store/svelte Install the package using pnpm. ```bash pnpm install @xstate/store-svelte ``` -------------------------------- ### Install @xstate/store-preact Source: https://stately.ai/docs/xstate-store/preact Install the @xstate/store-preact package using npm, pnpm, or yarn. ```bash npm install @xstate/store-preact ``` ```bash pnpm install @xstate/store-preact ``` ```bash yarn add @xstate/store-preact ``` -------------------------------- ### Install @xstate/store-react with npm Source: https://stately.ai/docs/xstate-store/react Install the @xstate/store-react package using npm. ```bash npm install @xstate/store-react ``` -------------------------------- ### Install @xstate/store-react with yarn Source: https://stately.ai/docs/xstate-store/react Install the @xstate/store-react package using yarn. ```bash yarn add @xstate/store-react ``` -------------------------------- ### Install @xstate/store-svelte with yarn Source: https://stately.ai/docs/xstate-store/svelte Install the package using yarn. ```bash yarn add @xstate/store-svelte ``` -------------------------------- ### Install @xstate/store with pnpm Source: https://stately.ai/docs/xstate-store Install the @xstate/store package using pnpm. ```bash pnpm install @xstate/store ``` -------------------------------- ### XState Store Primitive Atom Example Source: https://stately.ai/docs/xstate-store/compare-jotai Illustrates a primitive XState Store atom for managing a counter's state, showing how to get, set, and subscribe to its value. ```javascript const count = createAtom(0); count.get(); count.set((value) => value + 1); count.subscribe((value) => { console.log(value); }); ``` -------------------------------- ### Install @xstate/store-angular with yarn Source: https://stately.ai/docs/xstate-store/angular Install the package using yarn. ```bash yarn add @xstate/store-angular ``` -------------------------------- ### Install @xstate/store-angular with npm Source: https://stately.ai/docs/xstate-store/angular Install the package using npm. ```bash npm install @xstate/store-angular ``` -------------------------------- ### Install @xstate/store-react with pnpm Source: https://stately.ai/docs/xstate-store/react Install the @xstate/store-react package using pnpm. ```bash pnpm install @xstate/store-react ``` -------------------------------- ### Quick Start: Create and Use a Store Source: https://stately.ai/docs/xstate-store/preact Demonstrates creating a store with initial context and transitions, and using useSelector to display and update state within a Preact component. ```javascript import { createStore, useSelector } from '@xstate/store-preact'; const store = createStore({ context: { count: 0 }, on: { inc: (context, event: { by?: number }) => ({ count: context.count + (event.by ?? 1), }), }, }); function Counter() { const count = useSelector(store, (state) => state.context.count); return (

Count: {count}

); } ``` -------------------------------- ### Install @xstate/store-angular with pnpm Source: https://stately.ai/docs/xstate-store/angular Install the package using pnpm. ```bash pnpm install @xstate/store-angular ``` -------------------------------- ### useStore Source: https://stately.ai/docs/xstate-store/vue Creates a store instance for the current setup scope. Pass either a store config or store logic created with createStoreLogic(...). ```APIDOC ## useStore(configOrLogic, input?) ### Description Creates a store instance for the current setup scope. Pass either a store config or store logic created with `createStoreLogic(...)`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **configOrLogic** (object) - Required - The store configuration or store logic. - **input** (object) - Optional - Input for the store logic. ### Request Example ```javascript // Example usage within a Vue component import { createStoreLogic, useStore, useSelector } from '@xstate/store-vue'; const counterLogic = createStoreLogic({ context: (input) => ({ count: input.initialCount }), on: { inc: (context) => ({ count: context.count + 1 }), }, }); const store = useStore(counterLogic, { initialCount: 0 }); const count = useSelector(store, (state) => state.context.count); ``` ### Response #### Success Response (200) - **store** (object) - The created store instance. ``` -------------------------------- ### Jotai Derived Atom Example Source: https://stately.ai/docs/xstate-store/compare-jotai Shows how to create a derived atom in Jotai that computes its value based on another atom using the `get` function. ```javascript const countAtom = atom(0); const doubledAtom = atom((get) => get(countAtom) * 2); ``` -------------------------------- ### Quick Start: Create and Use an XState Store in Svelte Source: https://stately.ai/docs/xstate-store/svelte Demonstrates creating a store with initial context and actions, and using Svelte's useSelector to display and interact with the store's state. ```svelte

Count: {$count}

``` -------------------------------- ### XState Store Creation and Transition Example Source: https://stately.ai/docs/xstate-store/compare-zustand An XState Store configured with initial context and a named transition (`inc`) to update the state. ```javascript const store = createStore({ context: { count: 0 }, on: { inc: (context, event: { by: number }) => ({ count: context.count + event.by, }), }, }); store.trigger.inc({ by: 1 }); ``` -------------------------------- ### Basic Persist Setup Source: https://stately.ai/docs/xstate-store/persist Initializes a store with the persist extension, automatically saving and restoring state from localStorage. ```typescript import { createStore } from '@xstate/store'; import { persist } from '@xstate/store/persist'; const store = createStore({ context: { count: 0 }, on: { inc: (context) => ({ count: context.count + 1 }), }, }).with( persist({ name: 'counter' }), ); ``` -------------------------------- ### Strongly Typed State Machine with Setup Source: https://stately.ai/docs/xstate-store Defines a state machine with strong typing for context and events using the `setup` function from XState. This enhances type safety and provides better autocompletion and compile-time checks for machine configurations. ```typescript import { setup } from 'xstate'; const machine = setup({ types: { context: {} as { count: number; name: string }, events: {} as { type: 'inc'; by: number }, }, }).createMachine({ // Same as the previous example }); ``` -------------------------------- ### XState Store Persistence Extension Example Source: https://stately.ai/docs/xstate-store/compare-jotai Shows how to apply the persistence extension to an XState Store to enable state persistence, typically using named storage. ```javascript const store = createStore({ context: { count: 0 }, on: {}, }).with(persist({ name: 'count' })); ``` -------------------------------- ### Quick start Counter Component Source: https://stately.ai/docs/xstate-store/solid Demonstrates creating a store and using useSelector to display and update a counter. ```typescript import { createStore, useSelector } from '@xstate/store-solid'; const store = createStore({ context: { count: 0 }, on: { inc: (context, event: { by?: number }) => ({ count: context.count + (event.by ?? 1), }), }, }); function Counter() { const count = useSelector(store, (state) => state.context.count); return (

Count: {count()}

); } ``` -------------------------------- ### Pinia Extension Example Source: https://stately.ai/docs/xstate-store/compare-pinia Example of a Pinia extension using a plugin to persist store state to localStorage. ```typescript pinia.use(({ store }) => { store.$subscribe(() => { localStorage.setItem(store.$id, JSON.stringify(store.$state)); }); }); ``` -------------------------------- ### Create Store with Schema Validation (XState Store) Source: https://stately.ai/docs/xstate-store/compare-redux Example of creating an XState Store with schema validation for events. ```typescript const store = createStore({ schemas: { events: { increment: z.object({ by: z.number() }), }, }, context: { count: 0 }, on: {}, }).with(validateSchemas()); ``` -------------------------------- ### Recoil Atom and Selector Example Source: https://stately.ai/docs/xstate-store/compare-recoil Example of defining a Recoil atom for state and a selector for derived state. ```javascript const countState = atom({ key: 'count', default: 0, }); const doubledState = selector({ key: 'doubled', get: ({ get }) => get(countState) * 2, }); ``` -------------------------------- ### Jotai Persistence Example Source: https://stately.ai/docs/xstate-store/compare-jotai Illustrates how to use Jotai's `atomWithStorage` utility to create an atom that persists its state using local storage. ```javascript const persistedAtom = atomWithStorage('count', 0); ``` -------------------------------- ### XState Store Counter Example Source: https://stately.ai/docs/xstate-store/compare-pinia The equivalent counter store implemented using XState Store, showing context and event-driven updates. ```typescript const store = createStore({ context: { count: 0 }, on: { increment: (context, event: { by: number }) => ({ count: context.count + event.by, }), }, }); store.trigger.increment({ by: 1 }); ``` -------------------------------- ### XState Store React Adapter Example Source: https://stately.ai/docs/xstate-store/compare-jotai Demonstrates a React component using the XState Store React adapter's `useAtom` hook to subscribe to atom state. ```javascript function Counter() { const count = useAtom(countAtom); return {count}; } ``` -------------------------------- ### XState Store Reducer Atom Example Source: https://stately.ai/docs/xstate-store/compare-jotai Shows how to create a reducer atom in XState Store for managing state updates based on events, suitable for domain transitions. ```javascript const count = createReducerAtom(0, (state, event: { type: 'inc' }) => { if (event.type === 'inc') { return state + 1; } return state; }); count.send({ type: 'inc' }); ``` -------------------------------- ### useAtomState Source: https://stately.ai/docs/xstate-store/vue Creates or subscribes to an atom for the current setup scope. It returns the current readonly ref and the live atom instance. ```APIDOC ## useAtomState(atomOrConfig, input?) ### Description Creates or subscribes to an atom for the current setup scope. It returns the current readonly ref and the live atom instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **atomOrConfig** (object) - Required - The atom or atom configuration. - **input** (object) - Optional - Input for the atom config. ### Request Example ```javascript // Example usage within a Vue component import { createAtomConfig, useAtomState } from '@xstate/store-vue'; const countConfig = createAtomConfig((input) => input.initialCount); const [count, countAtom] = useAtomState(countConfig, { initialCount: 0 }); ``` ### Response #### Success Response (200) - **count** (Ref) - A readonly ref containing the atom's current value. - **countAtom** (object) - The live atom instance. ``` -------------------------------- ### Zustand Persistence Middleware Example Source: https://stately.ai/docs/xstate-store/compare-zustand Demonstrates how to use the `persist` middleware with Zustand to save and load state. This is useful for maintaining state across page reloads. ```javascript const useStore = create( persist( (set) => ({ count: 0, }), { name: 'counter' }, ), ); ``` -------------------------------- ### XState Store Async Atom Example Source: https://stately.ai/docs/xstate-store/compare-jotai Illustrates an asynchronous XState Store atom that fetches user data, providing explicit pending, done, and error snapshots. ```javascript const user = createAsyncAtom(async ({ signal }) => { const response = await fetch('/api/user', { signal }); return response.json(); }); ``` -------------------------------- ### Pinia Vue Integration with storeToRefs Source: https://stately.ai/docs/xstate-store/compare-pinia Integrates a Pinia store into a Vue component using setup script and storeToRefs. ```vue ``` -------------------------------- ### Async Storage Setup Source: https://stately.ai/docs/xstate-store/persist Sets up the persist extension with an async storage adapter like React Native's AsyncStorage, using `skipHydration` and manual rehydration. ```typescript import { persist, rehydrateStore, createJSONStorage, } from '@xstate/store/persist'; const store = createStore({ context: { count: 0 }, on: { inc: (context) => ({ count: context.count + 1 }), }, }).with( persist({ name: 'my-store', storage: createJSONStorage(() => AsyncStorage), skipHydration: true, }), ); await rehydrateStore(store); ``` -------------------------------- ### Solid Counter Store Integration Source: https://stately.ai/docs/xstate-store Example of integrating XState Store with a SolidJS application using the `@xstate/store-solid` package. Note the use of signals for reactive values. ```jsx import { createStore, useSelector } from '@xstate/store-solid'; const store = createStore({ context: { count: 0 }, on: { inc: (context, event: { by?: number }) => ({ count: context.count + (event.by ?? 1), }), }, }); function Counter() { const count = useSelector(store, (state) => state.context.count); return ; } ``` -------------------------------- ### Jotai React Integration Example Source: https://stately.ai/docs/xstate-store/compare-jotai Shows a simple React component using Jotai's `useAtom` hook to display and interact with atom state. ```javascript function Counter() { const [count] = useAtom(countAtom); return {count}; } ``` -------------------------------- ### Quick start: Counter component with XState Store Source: https://stately.ai/docs/xstate-store/react Demonstrates a basic counter component using createStore and useSelector from @xstate/store-react. Use this for simple global or shared state management. ```jsx import { createStore, useSelector } from '@xstate/store-react'; const store = createStore({ context: { count: 0 }, on: { inc: (context, event: { by?: number }) => ({ count: context.count + (event.by ?? 1), }), }, }); function Counter() { const count = useSelector(store, (state) => state.context.count); return (

Count: {count}

); } ``` -------------------------------- ### XState Store with Enqueued Effect Source: https://stately.ai/docs/xstate-store/compare-redux Example of handling asynchronous operations by enqueuing an effect within an XState Store transition. ```typescript const store = createStore({ context: { saved: false }, on: { save: (context, event, enqueue) => { enqueue.effect(async () => { await api.save(); }); return { saved: true }; }, }, }); ``` -------------------------------- ### Jotai Async Atom Example Source: https://stately.ai/docs/xstate-store/compare-jotai Demonstrates an asynchronous Jotai atom that fetches user data, integrating with React Suspense or using `loadable` for state management. ```javascript const userAtom = atom(async () => { const response = await fetch('/api/user'); return response.json(); }); ``` -------------------------------- ### Preact Counter Store Integration Source: https://stately.ai/docs/xstate-store Integrate XState Store with a Preact application using the `@xstate/store-preact` package. This example is similar to the React integration. ```jsx import { createStore, useSelector } from '@xstate/store-preact'; const store = createStore({ context: { count: 0 }, on: { inc: (context, event: { by?: number }) => ({ count: context.count + (event.by ?? 1), }), }, }); function Counter() { const count = useSelector(store, (state) => state.context.count); return ; } ``` -------------------------------- ### Create Reusable Store Logic with Initial Input Source: https://stately.ai/docs/xstate-store Define reusable store logic using `createStoreLogic`. The `context` can be a function of input, allowing each store instance to start with different context. ```javascript 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 ``` -------------------------------- ### XState Store Derived Atom Example Source: https://stately.ai/docs/xstate-store/compare-jotai Demonstrates creating a derived atom in XState Store that calculates its value by directly accessing another atom's value using `.get()`. ```javascript const count = createAtom(0); const doubled = createAtom(() => count.get() * 2); ``` -------------------------------- ### Vue Counter Store Integration Source: https://stately.ai/docs/xstate-store Integrate XState Store with a Vue application using the `@xstate/store-vue` package. This example uses the Composition API. ```vue ``` -------------------------------- ### Create Store with Schema Validation Source: https://stately.ai/docs/xstate-store/validate-schemas Demonstrates creating an XState Store with schema validation enabled for context and events using Zod. This setup checks incoming events at runtime. ```typescript import { createStore } from '@xstate/store'; import { validateSchemas } from '@xstate/store/validate'; import { z } from 'zod'; const store = createStore({ schemas: { context: z.object({ count: z.number() }), events: { inc: z.object({ by: z.number() }), }, }, context: { count: 0 }, on: { inc: (context, event) => ({ count: context.count + event.by }), }, }).with(validateSchemas()); store.trigger.inc({ by: 1 }); // ok store.trigger.inc({ by: 'two' as any }); // throws StoreValidationError ``` -------------------------------- ### Zustand State Type Definition Example Source: https://stately.ai/docs/xstate-store/compare-zustand Illustrates a basic TypeScript type definition for a Zustand store's state, including actions. ```typescript type State = { count: number; increment: (by: number) => void; }; ``` -------------------------------- ### Create and Use a Store Selector Source: https://stately.ai/docs/xstate-store Create a selector using `store.select()` to efficiently get and subscribe to specific parts of the store's state. Subscribers are only notified when the selected value changes. ```javascript import { createStore } from '@xstate/store'; const store = createStore({ context: { position: { x: 0, y: 0 }, name: 'John', age: 30, }, on: { positionUpdated: ( context, event: { position: { x: number; y: number } }, ) => ({ ...context, position: event.position, }), }, }); // Create a selector for the position const position = store.select((context) => context.position); // Get current value console.log(position.get()); // { x: 0, y: 0 } // Subscribe to changes position.subscribe((position) => { console.log('Position updated:', position); }); // When position updates, only position subscribers are notified store.trigger.positionUpdated({ position: { x: 100, y: 200 } }); // Logs: Position updated: { x: 100, y: 200 } ``` -------------------------------- ### Zustand Store for Status Updates Source: https://stately.ai/docs/xstate-store/compare-zustand A Zustand store example demonstrating a simple status update action. This pattern is suitable for straightforward state changes where explicit event handling is not required. ```javascript const useStore = create((set) => ({ status: 'idle', submit: () => set({ status: 'submitted' }), })); ``` -------------------------------- ### Jotai Primitive Atom Example Source: https://stately.ai/docs/xstate-store/compare-jotai Demonstrates a basic writable Jotai atom for managing a counter's state within a React component using the `useAtom` hook. ```javascript const countAtom = atom(0); function Counter() { const [count, setCount] = useAtom(countAtom); return ; } ``` -------------------------------- ### Pinia Action with Side Effect Source: https://stately.ai/docs/xstate-store/compare-pinia An example of a Pinia action that includes an asynchronous side effect. ```typescript actions: { async save() { await api.save(this.count); this.saved = true; }, } ``` -------------------------------- ### useStore Source: https://stately.ai/docs/xstate-store/solid Creates a store instance for the current Solid owner. It accepts either a store configuration object or store logic created with `createStoreLogic(...)`. ```APIDOC ## useStore(configOrLogic, input?) ### Description Creates a store instance for the current Solid owner. Pass either a store config or store logic created with `createStoreLogic(...)`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **configOrLogic**: Either a store configuration object or store logic created with `createStoreLogic(...)`. - **input** (Optional): Input values for the store logic. ### Request Example ```javascript import { createStoreLogic, useSelector, useStore } from '@xstate/store-solid'; const counterLogic = createStoreLogic({ context: (input: { initialCount: number }) => ({ count: input.initialCount, }), on: { inc: (context) => ({ count: context.count + 1 }), }, }); function Counter() { const store = useStore(counterLogic, { initialCount: 0 }); const count = useSelector(store, (state) => state.context.count); return ; } ``` ### Response #### Success Response (200) - **store**: The created store instance. #### Response Example ```javascript // Returns a store instance with trigger and other methods. ``` ``` -------------------------------- ### Full Reset of XState Store Context Source: https://stately.ai/docs/xstate-store/reset Demonstrates how to use the reset extension to return the store context to its initial state. Requires importing 'createStore' and 'reset'. ```javascript import { createStore } from '@xstate/store'; import { reset } from '@xstate/store/reset'; const store = createStore({ context: { count: 0 }, on: { inc: (context) => ({ count: context.count + 1 }), }, }).with(reset()); store.trigger.inc(); store.trigger.inc(); store.getSnapshot().context.count; // 2 store.trigger.reset(); store.getSnapshot().context.count; // 0 ``` -------------------------------- ### Vue Store Creation with Logic Source: https://stately.ai/docs/xstate-store/vue Creates a store instance using `useStore` with predefined logic, including an initial input for context. ```vue ``` -------------------------------- ### Create Store Logic with fromStore Source: https://stately.ai/docs/xstate-store Demonstrates the basic usage of `fromStore` to define store logic, which is then used to create a store actor via `createActor`. This is a simplified alternative to XState's `createMachine` for less complex state management needs. ```typescript import { fromStore } from '@xstate/store'; // Instead of: // const store = createStore({ const storeLogic = fromStore({ context: { // ... }, on: { // ... }, }); // Create the store (actor) const storeActor = createActor(storeLogic); ``` -------------------------------- ### Define Counter Slice (Redux Toolkit) Source: https://stately.ai/docs/xstate-store/compare-redux Example of defining a counter slice using Redux Toolkit's createSlice. ```typescript const counterSlice = createSlice({ name: 'counter', initialState, reducers: { increment: (state, action: PayloadAction) => {}, }, }); ``` -------------------------------- ### Redux Toolkit Async Thunk Example Source: https://stately.ai/docs/xstate-store/compare-redux Defines an asynchronous thunk using Redux Toolkit to increment a counter after a delay. ```javascript export const incrementLater = createAsyncThunk( 'counter/incrementLater', async (_, { dispatch }) => { await delay(1000); dispatch(counterSlice.actions.increment(1)); }, ); ``` -------------------------------- ### useStore(configOrLogic, input?) Source: https://stately.ai/docs/xstate-store/svelte Creates a component-scoped store instance from a store configuration or store logic. If the store logic requires input, the input argument is required. ```APIDOC ## useStore(configOrLogic, input?) ### Description Creates a component-scoped store instance from a store configuration or store logic. If the store logic requires input, the input argument is required. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **Store Instance**: A component-scoped XState store instance. ### Response Example ```javascript ``` ``` -------------------------------- ### XState Store Extension with Persistence Source: https://stately.ai/docs/xstate-store/compare-redux Creates an XState Store and applies the persistence extension to it. ```javascript const store = createStore({ context: { count: 0 }, on: {}, }).with(persist({ name: 'counter' })); ``` -------------------------------- ### Use useStore with createStoreLogic Source: https://stately.ai/docs/xstate-store/solid Creates a store instance for the current Solid owner using store logic. Pass store logic created with `createStoreLogic(...)` and optional input. ```typescript import { createStoreLogic, useSelector, useStore } from '@xstate/store-solid'; const counterLogic = createStoreLogic({ context: (input: { initialCount: number }) => ({ count: input.initialCount, }), on: { inc: (context) => ({ count: context.count + 1 }), }, }); function Counter() { const store = useStore(counterLogic, { initialCount: 0 }); const count = useSelector(store, (state) => state.context.count); return ; } ``` -------------------------------- ### Validate Emitted Events Source: https://stately.ai/docs/xstate-store/validate-schemas Demonstrates setting up schema validation for emitted events. This example defines a schema for the 'counted' emitted event and uses `enq.emit` to trigger it. ```typescript const store = createStore({ schemas: { emitted: { counted: z.object({ count: z.number() }), }, }, context: { count: 0 }, on: { inc: (context, event: { by: number }, enq) => { enq.emit.counted({ count: context.count + event.by }); return { count: context.count + event.by }; }, }, }).with(validateSchemas()); ``` -------------------------------- ### Migrate undoRedo to extension form with .with() Source: https://stately.ai/docs/xstate-store/migration The `undoRedo` functionality is now an extension. Use `.with(undoRedo())` when creating the store instead of passing it directly to `createStore`. ```javascript - 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()); ``` -------------------------------- ### useStore Source: https://stately.ai/docs/xstate-store/preact Creates a component-scoped store instance from a store config or store logic. ```APIDOC ## useStore(configOrLogic, input?) ### Description Creates a component-scoped store instance from a store config or store logic. If the store logic requires input, the `input` argument is required. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { useStore } from '@xstate/store-preact'; import { createStoreLogic } from '@xstate/store'; // Assuming createStoreLogic is imported from @xstate/store const counterLogic = createStoreLogic({ context: (input) => ({ count: input.initialCount }), on: { inc: (context) => ({ count: context.count + 1 }), }, }); function Counter() { const store = useStore(counterLogic, { initialCount: 0 }); // ... use store } ``` ### Response #### Success Response - **store** (object) - A component-scoped XState Store instance. ``` -------------------------------- ### Migrate createStore from (context, transitions) to config object Source: https://stately.ai/docs/xstate-store/migration The `createStore` API has been updated. Use the config object form with `context` and `on` properties instead of separate context and transitions arguments. ```javascript - const store = createStore( - { count: 0 }, - { - inc: (context) => ({ count: context.count + 1 }) - } - ); + const store = createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } + }); ``` -------------------------------- ### Selector with Custom Equality Function (X Coordinate) Source: https://stately.ai/docs/xstate-store Provide a custom equality function to `store.select()` to control notification triggers. This example only notifies subscribers if the 'x' coordinate changes. ```javascript const position = store.select( (context) => context.position, // Only notify if x coordinate changes (prev, next) => prev.x === next.x, ); ``` -------------------------------- ### Forcing Immediate Storage Write Source: https://stately.ai/docs/xstate-store/persist Demonstrates how to force an immediate write to storage using `flushStorage`, typically used before a page unload. ```typescript import { flushStorage } from '@xstate/store/persist'; window.addEventListener('beforeunload', () => { flushStorage(store); }); ``` -------------------------------- ### Create XState Actor from Store Logic Source: https://stately.ai/docs/xstate-store Use `fromStore` to create XState-compatible store logic. This logic can then be passed to `createActor` to instantiate a store actor. This is useful for integrating simple store logic into existing XState applications. ```typescript import { fromStore } from '@xstate/store'; import { createActor } from 'xstate'; // Instead of: // const store = createStore( ... }; const storeLogic = fromStore({ context: { count: 0, incremented: false /* ... */ }, on: { inc: { count: (context, event) => context.count + 1, // Static values do not need to be wrapped in a function incremented: true, }, }, }); const store = createActor(storeLogic); store.subscribe((snapshot) => { console.log(snapshot); }); store.start(); store.send({ type: 'inc', }); ``` -------------------------------- ### Use Store Logic with Input in React Hook Source: https://stately.ai/docs/xstate-store Demonstrates how to use `useStore` hook from `@xstate/store-react` with store logic that requires input for initialization. ```javascript import { createStoreLogic, useStore } from '@xstate/store-react'; const counterLogic = createStoreLogic({ context: (input: { initialCount: number }) => ({ count: input.initialCount, }), on: { inc: (context) => ({ count: context.count + 1, }), }, }); function Counter() { const store = useStore(counterLogic, { initialCount: 0 }); } ``` -------------------------------- ### Provide Input to Store Actor Logic Source: https://stately.ai/docs/xstate-store Utilize a context function within `fromStore` to dynamically initialize the actor's context based on provided input. This allows for parameterized store actors, where initial state depends on external values passed during actor creation. ```typescript import { fromStore } from '@xstate/store'; const storeLogic = fromStore({ context: (initialCount: number) => ({ count: initialCount, }), on: { // ... }, }); const actor = createActor(storeLogic, { input: 42, }); ``` -------------------------------- ### Create Store Logic with Input for Context Source: https://stately.ai/docs/xstate-store Define store logic where the initial context is determined by an input object. This allows for flexible initialization of store instances. ```javascript import { createStoreLogic } from '@xstate/store'; const counterLogic = createStoreLogic({ context: (input: { initialCount: number }) => ({ count: input.initialCount, }), on: { inc: (context) => ({ count: context.count + 1, }), }, }); const store = counterLogic.createStore({ initialCount: 0 }); ``` -------------------------------- ### Use useStore with Store Logic Source: https://stately.ai/docs/xstate-store/preact Creates a component-scoped store instance using createStoreLogic and subscribes to its state with useSelector. The store logic requires an input for initial context. ```javascript import { createStoreLogic, useSelector, useStore } from '@xstate/store-preact'; const counterLogic = createStoreLogic({ context: (input: { initialCount: number }) => ({ count: input.initialCount, }), on: { inc: (context) => ({ count: context.count + 1 }), }, }); function Counter() { const store = useStore(counterLogic, { initialCount: 0 }); const count = useSelector(store, (state) => state.context.count); return ; } ``` -------------------------------- ### Compute Next State from Initial Snapshot Source: https://stately.ai/docs/xstate-store Determine the next state and effects from the store's initial state using `store.getInitialSnapshot()` and `store.transition()`. ```javascript const initialSnapshot = store.getInitialSnapshot(); const [nextState, effects] = store.transition(initialSnapshot, { type: 'inc', by: 1, }); ``` -------------------------------- ### Injecting Store State as Angular Signals Source: https://stately.ai/docs/xstate-store/angular Demonstrates how to use `injectStore` to create Angular signals from XState store state. Shows selection of specific properties and custom comparison functions. ```typescript import { Component } from '@angular/core'; import { injectStore } from '@xstate/store-angular'; @Component({ selector: 'app-counter', template: `
Count: {{ count() }}
`, }) export class CounterComponent { count = injectStore(store, (state) => state.context.count); user = injectStore( store, (state) => state.context.user, (prev, next) => prev.id === next.id ); snapshot = injectStore(store); } ``` -------------------------------- ### useSelector(store, selector?, compare?) Source: https://stately.ai/docs/xstate-store/svelte Creates a Svelte readable store that subscribes to an XState store and returns a selected value. It can optionally take a selector function and a comparison function. ```APIDOC ## useSelector(store, selector?, compare?) ### Description Creates a Svelte readable store that subscribes to an XState store and returns a selected value. It can optionally take a selector function and a comparison function. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **Readable Store**: A Svelte readable store that emits selected values from the XState store. ### Response Example ```javascript
Count: {$count}
``` ``` -------------------------------- ### Compute Next State and Effects with store.transition Source: https://stately.ai/docs/xstate-store Use `store.transition(state, event)` to compute the next state and effects without changing the store's actual state. Useful for debugging and testing. ```javascript const store = createStore({ context: { count: 0 }, schemas: { emitted: { incremented: z.object({ by: z.number() }), }, }, on: { inc: (context, event: { by: number }, enqueue) => { enqueue.emit.incremented({ by: event.by }); enqueue.effect(() => { setTimeout(() => { console.log('incremented'); }, 1000); }); return { ...context, count: context.count + event.by, }; }, }, }); const snapshot = store.getSnapshot(); const [nextState, effects] = store.transition(snapshot, { type: 'inc', by: 1, }); console.log(nextState.context); // => { count: 1 } console.log(effects); // => [ // { type: 'incremented', by: 1 }, // Function // ] // The store's state is unchanged console.log(store.getSnapshot().context); // => { count: 0 } ``` -------------------------------- ### Migrate createStoreWithProducer to createStore with Immer Source: https://stately.ai/docs/xstate-store/migration The `createStoreWithProducer` API is removed. Use the `createStore` API and call your producer (e.g., Immer's `produce`) inside transition handlers. When using Immer, return `undefined` from the transition before calling `produce(...)` if the event should not result in a transition. ```javascript - 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++; + }) } }); ``` -------------------------------- ### Use useStore to create a component-scoped XState Store in Svelte Source: https://stately.ai/docs/xstate-store/svelte Creates a component-scoped store instance from a store config or store logic, optionally accepting input for the store logic. ```svelte ``` -------------------------------- ### Update import path for framework packages Source: https://stately.ai/docs/xstate-store/migration The import paths for framework-specific packages have changed. Use `@xstate/store-react` and `@xstate/store-solid` instead of `@xstate/store/react` and `@xstate/store/solid`. ```javascript - import { useSelector } from '@xstate/store/react'; + import { useSelector } from '@xstate/store-react'; ``` -------------------------------- ### useAtom Source: https://stately.ai/docs/xstate-store/preact Subscribes to an atom and returns its value. You can pass an existing atom, or an atom config created with `createAtomConfig(...)`. ```APIDOC ## useAtom(atomOrConfig, selectorOrInput?, compare?) ### Description Subscribes to an atom and returns its value. You can pass an existing atom, or an atom config created with `createAtomConfig(...)`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { useAtom, createAtomConfig } from '@xstate/store-preact'; const countConfig = createAtomConfig((input) => input.initialCount); function Counter() { const count = useAtom(countConfig, { initialCount: 0 }); // ... use count } ``` ### Response #### Success Response - **atomValue** (any) - The current value of the atom. ``` -------------------------------- ### XState Store Extension with Persistence Source: https://stately.ai/docs/xstate-store/compare-pinia Applies a persistence extension to an XState store. ```typescript const store = createStore({ context: { count: 0 }, on: {}, }).with(persist({ name: 'counter' })); ``` -------------------------------- ### useAtom Source: https://stately.ai/docs/xstate-store/solid Subscribes to an atom and returns a Solid accessor. This hook can accept an existing atom or an atom configuration created with `createAtomConfig(...)`. ```APIDOC ## useAtom(atomOrConfig, selectorOrInput?, compare?) ### Description Subscribes to an atom and returns a Solid accessor. You can pass an existing atom, or an atom config created with `createAtomConfig(...)`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **atomOrConfig**: An existing atom or an atom configuration created with `createAtomConfig(...)`. - **selectorOrInput** (Optional): A selector function or input values for the atom configuration. - **compare** (Optional): A comparison function to determine if the selected value has changed. ### Request Example ```javascript import { createAtomConfig, useAtom } from '@xstate/store-solid'; const countConfig = createAtomConfig((input: { initialCount: number }) => { return input.initialCount; }); function Counter() { const count = useAtom(countConfig, { initialCount: 0 }); return
Count: {count()}
; } ``` ### Response #### Success Response (200) - **accessor**: A Solid accessor that returns the atom's value. #### Response Example ```javascript // The returned value is a Solid accessor, e.g., count() ``` ```