### Install @rkrupinski/stan Source: https://github.com/rkrupinski/stan/blob/master/README.md Install the Stan library using npm. This command is used to add the package to your project's dependencies. ```sh npm install @rkrupinski/stan ``` -------------------------------- ### Install Stan with Bun Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/getting-started/installation.mdx Use this command to install Stan via Bun. This command adds the package to your project's dependencies. ```sh bun add @rkrupinski/stan ``` -------------------------------- ### Install Stan with npm Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/getting-started/installation.mdx Use this command to install Stan via npm. Ensure you are using the `--save` flag to add it to your project's dependencies. ```sh npm install --save @rkrupinski/stan ``` -------------------------------- ### Basic Usage Example Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selectorFamily.md Demonstrates how to use `selectorFamily` to create a selector that fetches user data by ID. ```APIDOC ## Example: Get user by id ```ts const userById = selectorFamily, string>( userId => () => getUser(userId) ); ``` ``` -------------------------------- ### Example with Abort Signal Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selectorFamily.md Shows how to integrate an abort signal with `selectorFamily` to cancel pending requests. ```APIDOC ## Example: Abort pending request ```ts const userById = selectorFamily, string>( userId => ({ signal }) => getUser(userId, { signal }) ); ``` ``` -------------------------------- ### Initialize atomFamily with a function Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atomFamily.md Example of initializing an atomFamily where the initial value is derived from the parameter. This is useful when atoms need different starting values. ```typescript type User = { id: string; score: number; }; const scores = atomFamily(user => user.score); ``` -------------------------------- ### Install Stan with pnpm Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/getting-started/installation.mdx Use this command to install Stan via pnpm. This command adds the package to your project's dependencies. ```sh pnpm add @rkrupinski/stan ``` -------------------------------- ### Install Stan with Yarn Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/getting-started/installation.mdx Use this command to install Stan via Yarn. This command adds the package to your project's dependencies. ```sh yarn add @rkrupinski/stan ``` -------------------------------- ### React Counter Example with Stan Source: https://github.com/rkrupinski/stan/blob/master/README.md A basic React component demonstrating Stan's state management. It uses `atom` for state, `selector` for derived state, and `useStan`/`useStanValue` hooks for integration. Ensure you have installed `@rkrupinski/stan/react` for the hooks. ```jsx import { atom, selector } from "@rkrupinski/stan"; import { useStan, useStanValue } from "@rkrupinski/stan/react"; const count = atom(0); const doubled = selector(({ get }) => get(count) * 2); function Counter() { const [value, setValue] = useStan(count); const double = useStanValue(doubled); return ( <>

Doubled: {double}

); } ``` -------------------------------- ### Example with LRU Cache Policy Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selectorFamily.md Illustrates configuring `selectorFamily` with an LRU cache policy to limit the number of cached requests. ```APIDOC ## Example: Cache up to 5 requests ```ts const userById = selectorFamily, string>( userId => ({ signal }) => getUser(userId, { signal }), { cachePolicy: { type: 'lru', maxSize: 5, }, }, ); ``` ``` -------------------------------- ### Install Stan Skill for AI Agents Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/getting-started/agents.md Install the Stan skill for AI coding agents using npx. This command adds the skill to your agent, enabling it to access Stan-specific guidance. ```bash npx skills add rkrupinski/stan ``` -------------------------------- ### Example Usage of useStanCallback Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md Demonstrates how to use useStanCallback to create a memoized function for refreshing a user state based on user ID. This example assumes 'user' is a selectorFamily and 'users' is an array of user objects. ```tsx const user = selectorFamily, string>( userId => () => loadUser(userId), ); function MyComponent() { const reloadUser = useStanCallback(({ refresh }) => (userId: string) => { refresh(user(userId)); }); return (
    {users.map(({ id, name }) => (
  • {name}{' '}
  • ))}
); } ``` -------------------------------- ### Example Usage of StanProvider Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md Shows how to wrap your application with StanProvider, optionally providing a custom store instance created with makeStore(). This is essential for SSR or dynamic store switching. ```tsx const myStore = makeStore(); function MyApp() { return ( ); } ``` -------------------------------- ### Example with TTL and LRU Cache Policy Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selectorFamily.md Demonstrates setting a Time-To-Live (TTL) for cached requests when using an LRU cache policy. ```APIDOC ## Example: Refresh each cached request after a minute ```ts const userById = selectorFamily, string>( userId => ({ signal }) => getUser(userId, { signal }), { cachePolicy: { type: 'lru', maxSize: 5, ttl: 60_000, }, }, ); ``` ``` -------------------------------- ### Example Usage with React and Vue Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atom.md Demonstrates how to use Stan atoms with React and Vue components for reading and writing atom values. ```APIDOC ## Example Usage ### Description Illustrates how to create and interact with Stan atoms within React and Vue applications. ### React Example ```tsx import { useStan } from 'your-stan-library'; // Assuming useStan is exported import { myAtom } from './atoms'; // Assuming myAtom is defined elsewhere function MyComponent() { const [value, setValue] = useStan(myAtom); return ( setValue(e.target.valueAsNumber)} /> ); } ``` ### Vue Example ```vue ``` ``` -------------------------------- ### Provide Stan in Vue/Nuxt Setup Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/guides/ssr.md Alternatively, in Vue/Nuxt, you can call provideStan() within the setup function of your root component to achieve state scoping and isolation per request during server-side rendering. ```vue ``` -------------------------------- ### Example: Mapping Selector Result Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selectorFamily.md Shows how to map the result of a `selectorFamily` to a different value, for instance, extracting just the user's name. ```APIDOC ## Example: Map the result to a different value ```ts const userNameById = selectorFamily, string>( userId => async ({ get }) => { const { name } = await get(userById(userId)); return name; }, ); ``` ``` -------------------------------- ### Define a basic selector Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selector.md Use `selector` to define a derived state value. This example computes a static sum. ```typescript const selector: ( selectorFn: SelectorFn, options?: SelectorOptions, ) => Scoped>; const sum = selector(() => 40 + 2); ``` -------------------------------- ### Initialize atomFamily with a default number Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atomFamily.md Example of initializing an atomFamily to track scores, where each atom defaults to 0. ```typescript const scores = atomFamily(0); ``` -------------------------------- ### Provide Stan Store with provideStan Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md An alternative to `StanProvider`, this function can be called within a component's `setup()` to provide a store to its descendants. It accepts an optional `Store` instance. ```typescript const provideStan: (store?: Store) => void; ``` ```vue ``` -------------------------------- ### Create Callbacks with State Helpers using useStanCallback Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Returns a callback with access to Stan state helper functions like `get`, `set`, `reset`, and `refresh`. The factory function receives these helpers and returns your callback. Unlike React's version, it does not take a `deps` array. ```typescript const useStanCallback: ( factory: (helpers: StanCallbackHelpers) => (...args: A) => R, ) => (...args: A) => R; ``` ```typescript (scopedState: Scoped>) => T; ``` ```typescript ( scopedState: Scoped>, valueOrUpdater: T | ((currentValue: T) => T), ) => void ``` ```typescript (scopedState: Scoped>) => void ``` ```typescript (scopedState: Scoped>) => void ``` ```vue ``` -------------------------------- ### Define an asynchronous selector Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selector.md Selectors can be asynchronous, returning Promises. Use `async/await` with `get` to fetch data. The `AbortSignal` can be used to cancel ongoing operations. ```typescript const num1 = selector(() => getNum1()); const num2 = selector(() => getNum2()); const sum = selector(async ({ get }) => { const [n1, n2] = await Promise.all([get(num1), get(num2)]); return n1 + n2; }); ``` -------------------------------- ### Define a selector with dynamic dependencies Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selector.md Selectors can depend on other state primitives like atoms. The `get` function is used to access these dependencies, triggering re-evaluation when they change. ```typescript const num1 = atom(40); const num2 = atom(2); const sum = selector(({ get }) => get(num1) + get(num2)); ``` -------------------------------- ### useStanCallback Hook Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md Provides a memoized callback with access to Stan state helper functions for setting, refreshing, and getting state values. ```APIDOC ## `useStanCallback` Returns a memoized callback with access to helper functions for interacting with Stan state (setting, refreshing, etc.). ### Signature ```ts const useStanCallback: ( factory: (helpers: StanCallbackHelpers) => (...args: A) => R, deps?: DependencyList, ) => (...args: A) => R; ``` ### Parameters - `factory` – A curried callback function, where: - `helpers` – State helpers: - `get` – A function for getting [`State`](./state.md#statet) value, with the following signature: ```ts (scopedState: Scoped>) => T; ``` - `set` – A function for setting [`WritableState`](./state.md#writablestatet), with the following signature: ```ts ( scopedState: Scoped>, valueOrUpdater: T | ((currentValue: T) => T), ) => void ``` - `reset` – A function for [resetting](./utils.md#reset) [`WritableState`](./state.md#writablestatet), with the following signature: ```ts (scopedState: Scoped>) => void ``` - `refresh` – A function for [refreshing](./utils.md#refresh) [`ReadonlyState`](./state.md#readonlystatet), with the following signature: ```ts (scopedState: Scoped>) => void ``` - `deps?` – An array of dependencies (see [`useCallback`](https://react.dev/reference/react/useCallback)). ### Example ```tsx const user = selectorFamily, string>( userId => () => loadUser(userId), ); function MyComponent() { const reloadUser = useStanCallback(({ refresh }) => (userId: string) => { refresh(user(userId)); }); return (
    {users.map(({ id, name }) => (
  • {name}
  • ))}
); } ``` ``` -------------------------------- ### Store Instantiation and Destruction Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/store.md Shows how to create a new Store instance with options and how to destroy it to free memory. ```ts const myStore = makeStore({ tag: 'Data' }); myStore.destroy(); // Free memory ``` -------------------------------- ### Atom Creation and Options Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atom.md Defines the `atom` function for creating state containers and explains its initialization and configuration options. ```APIDOC ## `atom` Function ### Description Creates a state atom, which is a value container with no dependencies, acting as a source vertex in the Stan state graph. Designed for synchronous state but adaptable for asynchronous operations. ### Method `atom(initialValue: T, options?: AtomOptions) => Scoped>` ### Parameters #### Parameters - **initialValue** (T) - Required - The initial value for the atom. - **options?** (AtomOptions) - Optional - Configuration options for the atom: - **tag?** (string) - Optional - A string appended to the `key` for debugging purposes. - **effects?** (Array>) - Optional - An array of atom effects to be applied. - **areValuesEqual?** ((a: T, b: T) => boolean) - Optional - A function to compare consecutive values. Defaults to `a === b`. If it returns true, the value is considered unchanged, and subscribers are not notified. ### Request Example ```ts const myAtom = atom(42); const myAtomWithLogger = atom(42, { effects: [ ({ onSet }) => { onSet(newValue => { console.log('value changed:', newValue); }); }, ], }); ``` ### Response #### Success Response (200) Returns a `Scoped>` object representing the created atom. ``` -------------------------------- ### useStanStore Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md A low-level composable to access the current Stan store injection. Use with caution as it's considered unstable. ```APIDOC ## `useStanStore` In rare cases where you need to peek into the current Stan store injection, here's how you can do it. ```ts const useStanStore: () => StanStoreInjection; ``` `StanStoreInjection` fields: - `store` - A [`ComputedRef`](https://vuejs.org/api/reactivity-core.html#computed) wrapping the current [`Store`](./store.md#the-store-class) instance. :::info `useStanStore` is a low-level API and should therefore be considered unstable. ::: ``` -------------------------------- ### Get and Set Stan State with useStan Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md Combines useStanValue and useSetStanValue, similar to React's useState. Does not work with ReadonlyState. ```typescript const useStan: ( scopedState: Scoped>, ) => readonly [T, SetterOrUpdater]; ``` ```tsx const myAtom = atom(42); function MyComponent() { const [value, setValue] = useStan(myAtom); return ( <>
{value}
); } ``` -------------------------------- ### Reactive Inputs with Computed Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Demonstrates how to use computed properties with Stan composables to ensure reactivity when feeding parameters to Stan functions. ```APIDOC ## Reactive Inputs with Computed All value-returning composables ([`useStan`](#usestan), [`useStanValue`](#usestanvalue), [`useStanValueAsync`](#usestanvalueasync), [`useStanRefresh`](#usestanrefresh), [`useStanReset`](#usestanreset)) accept either a plain [`Scoped>`](./state.md) or a `Ref>>`. Wrap family calls in `computed` to feed a reactive parameter - the composable will re-subscribe automatically whenever the underlying scoped state changes. ### Request Example ```vue ``` ``` -------------------------------- ### Get Stan State Value with useStanValue Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md Returns the value of any Stan state and subscribes to changes. Works with atoms, atomFamilies, selectors, and selectorFamilies. ```typescript const useStanValue: (scopedState: Scoped>) => T; ``` ```tsx const myAtom = atom(42); function MyComponent() { const value = useStanValue(myAtom); return

{value}

; } ``` -------------------------------- ### Provide Stan Store with StanProvider Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Wraps a component subtree to provide a specific store instance. If no `store` prop is provided, it creates an isolated store. This is useful for SSR or dynamic store switching. Use `:key` to force recreation of the subtree. ```typescript const StanProvider: DefineComponent; ``` ```vue ``` -------------------------------- ### Get Stan State Value Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md A helper function within useStanCallback to retrieve the current value of a Stan state. Ensure the provided state is correctly scoped. ```typescript (scopedState: Scoped>) => T; ``` -------------------------------- ### Create an atom with a logger effect Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atom.md Initialize an atom with an effect that logs value changes to the console. This demonstrates how to integrate side effects during atom creation. ```typescript const myAtom = atom(42, { effects: [ ({ onSet }) => { onSet(newValue => { console.log('value changed:', newValue); }); }, ], }); ``` -------------------------------- ### provideStan Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Provides a Stan store to descendant components, serving as an alternative to wrapping the tree with StanProvider. ```APIDOC ## `provideStan` An alternative to wrapping your tree in [`StanProvider`](#stanprovider): call `provideStan` in a component's `setup()` to provide a store to descendants. ```ts const provideStan: (store?: Store) => void; ``` ### Example ```vue ``` ``` -------------------------------- ### Define a basic atom Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atom.md Use the `atom` function to create a state container with an initial value. This is suitable for simple, synchronous state management. ```typescript const atom: ( initialValue: T, options?: AtomOptions, ) => Scoped>; ``` -------------------------------- ### Update atom value in React Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atomFamily.md Demonstrates how to use the useStan hook to get and update an atom's value within a React component. The setScore function allows updating the previous value. ```tsx const Scoreboard: FC<{ user: User }> = ({ user }) => { const [score, setScore] = useStan(scores(user)); return ( <>

{score}

); }; ``` -------------------------------- ### useStanReset Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Wraps the reset utility to provide a function that resets WritableState. Works with atom and atomFamily. ```APIDOC ## `useStanReset` Wraps [`reset`](./utils.md#reset) and returns a function that resets [`WritableState`](./state.md#writablestatet). Works with: [`atom`](./atom.md), [`atomFamily`](./atomFamily.md) ```ts const useStanReset: (scopedState: Scoped> | Ref>>) => () => void; ``` ### Example ```vue ``` ``` -------------------------------- ### Create a number atom Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atom.md Instantiate an atom to hold a number. This is a fundamental use case for managing primitive state. ```typescript const myAtom = atom(42); ``` -------------------------------- ### useStanReset Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md Provides a function to reset WritableState to its initial value. ```APIDOC ## `useStanReset` Hook ### Description Wraps [`reset`](./utils.md#reset) and returns a function that resets [`WritableState`](./state.md#writablestatet). Works with: [`atom`](./atom.md), [`atomFamily`](./atomFamily.md) ### Signature ```ts const useStanReset: (scopedState: Scoped>) => () => void; ``` ### Example ```tsx import { atom } from "@rkrupinski/stan"; import { useStan, useStanReset } from "@rkrupinski/stan/react"; const counter = atom(0); function MyComponent() { const [value, setValue] = useStan(counter); const resetValue = useStanReset(counter); return ( <>
{value}
); } ``` ``` -------------------------------- ### Atom Effects Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atom.md Explains the concept and structure of atom effects, which allow for initialization, side effects, and value updates. ```APIDOC ## Atom Effects ### Description Atom effects are abstractions that enable initializing atoms, executing code upon value changes, and updating atom values in response to events. Multiple effects can be defined and are processed sequentially. ### Type Definition ```ts type AtomEffect = (param: { init(value: T): void; set: SetterOrUpdater; onSet(cb: (value: T) => void): void; }) => void; ``` ### Parameters #### Effect Parameters - **init** ((value: T) => void) - A function to initialize the atom's value. Must be called synchronously during effect execution. Subsequent calls or asynchronous calls are ignored. - **set** (SetterOrUpdater) - A function to update the atom's value. Intended for asynchronous use after initialization. Calling `set` does not trigger `onSet` but notifies subscribers. - **onSet** ((cb: (value: T) => void) => void) - A method to subscribe to atom value changes. Accepts a callback that is invoked with the new value, unless the change originated from within the effect via `set`. ``` -------------------------------- ### useStanCtx Hook Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md A low-level hook to access the current Stan context, primarily for retrieving the current Store instance. ```APIDOC ## `useStanCtx` In rare cases where you need to peek into the current Stan context, here's how you can do it. ### Signature ```ts const useStanCtx: () => StanCtxType; ``` `StanCtxType` fields: - `store` - The current [`Store`](./store.md#the-store-class) instance. :::info `useStanCtx` is a low-level API and should therefore be considered unstable. ::: ``` -------------------------------- ### `selectorFamily` Function Signature Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selectorFamily.md The `selectorFamily` function takes a selector family function and optional configuration options, returning a memoized function that generates selectors based on a parameter. ```APIDOC ## `selectorFamily` ### Signature ```ts selectorFamily: ( selectorFamilyFn: SelectorFamilyFn, options?: SelectorFamilyOptions

) => (param: P) => Scoped>; ``` ### Parameters - `selectorFamilyFn` (): A function that takes a serializable parameter `P` and returns a selector function. - `options` (optional): Configuration options for the selector family. - `tag` (string | (param: P) => string, optional): A string identifier for the selector, or a function to generate it based on the parameter. - `areValuesEqual` ((newValue: T, oldValue: T) => boolean, optional): A function to compare consecutive selector values. - `cachePolicy` (object, optional): Configuration for the selector family's cache. - `type` ('keep-all' | 'most-recent' | 'lru'): The caching strategy. - `maxSize` (number, optional): Required if `type` is 'lru'. Specifies the maximum number of cached selector instances. - `ttl` (number, optional): Time-to-live in milliseconds for cache entries. ``` -------------------------------- ### Scoped Atom Usage Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/store.md Demonstrates how Scoped works by accessing and modifying an atom's state within different store contexts. ```ts const myAtom = atom(42); myAtom(storeA).get(); // 42 myAtom(storeA).set(prev => prev + 1); myAtom(storeB).get(); // 42 ``` -------------------------------- ### StanProvider Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Provides a Stan store to the Vue component tree. Can be used to supply a custom store or create an isolated store. ```APIDOC ## `StanProvider` Stan, by default, operates in provider-less mode, using [`DEFAULT_STORE`](./store.md#the-store-class). However, if you need to supply a different store (e.g., for [SSR](../guides/ssr.md)) or switch stores dynamically, `StanProvider` comes in handy. Using `StanProvider` creates an isolation boundary: - **No provider** - composables use `DEFAULT_STORE` - **`StanProvider` without `store` prop** - creates a fresh, isolated store - **`StanProvider` with `store` prop** - uses the provided store :::info Composables track the current store through Vue's reactivity - changing `StanProvider`'s `:store` prop re-subscribes them automatically. Use `:key` on `StanProvider` only when you actually want to tear down and recreate the subtree (e.g., to discard local component state alongside the store switch). ::: ```ts const StanProvider: DefineComponent; ``` Props: - `store?` - A [`Store`](./store.md#the-store-class) instance. ### Example ```vue ``` ``` -------------------------------- ### Selector API Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selector.md The `selector` function creates a derived state that can compute values based on other states or selectors. It supports asynchronous operations and dynamic dependency tracking. ```APIDOC ## `selector` Function ### Description Creates a derived state that computes its value based on other states or selectors. It can handle synchronous or asynchronous computations and automatically tracks dependencies. ### Method `selector` ### Parameters #### Function Signature ```ts selector: ( selectorFn: SelectorFn, options?: SelectorOptions ) => Scoped>; ``` #### `selectorFn` - **Type**: `SelectorFn` - **Description**: The function that produces the derived value. It is invoked whenever the selector needs to re-evaluate. It has the signature `(arg: { get: GetFn; signal: AbortSignal }) => T`. - **`get`** (GetFn): A getter function to consume dependencies (atoms or other selectors). Calling `get` with a state instance adds it to the selector's dependency set. The dependency graph is dynamic and updates automatically. - **`signal`** (AbortSignal): An `AbortSignal` associated with the current `selectorFn` call. It is aborted on the next invocation, useful for canceling ongoing work. #### `options` - **Type**: `SelectorOptions` (optional) - **Description**: Configuration options for the selector. - **`tag`** (string, optional): Appended to the `key` for debugging purposes. - **`areValuesEqual`** ((a: T, b: T) => boolean, optional): A function to compare consecutive values. Defaults to `a === b`. If it returns true, subscribers are not notified. ### Request Example #### Basic Usage ```ts const sum = selector(() => 40 + 2); ``` #### Dynamic Numbers ```ts const num1 = atom(40); const num2 = atom(2); const sum = selector(({ get }) => get(num1) + get(num2)); ``` #### Asynchronous Numbers ```ts const num1 = selector(() => getNum1()); const num2 = selector(() => getNum2()); const sum = selector(async ({ get }) => { const [n1, n2] = await Promise.all([get(num1), get(num2)]); return n1 + n2; }); ``` ### Response #### Success Response - **Type**: `Scoped>` - **Description**: A state object representing the derived value. #### Response Example (Conceptual - the actual return is a state object) ```json { "value": "derived_value" } ``` ### See Also - [`selectorFamily`](./selectorFamily.md) - [Using Stan with React](./react.md) - [Using Stan with Vue](./vue.md) ``` -------------------------------- ### Define an atom with effects Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atom.md Configure an atom with effects to handle side effects like logging or external storage. The `onSet` callback within effects allows for reacting to value changes. ```typescript type AtomEffect = (param: { init(value: T): void; set: SetterOrUpdater; onSet(cb: (value: T) => void): void; }) => void; ``` -------------------------------- ### useStanValueAsync API Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Handles asynchronous state, returning a Ref with loading, ready, or error states. ```APIDOC ## `useStanValueAsync` API Wraps [`ReadonlyState`](./state.md#readonlystatet) whose type extends `PromiseLike` in a readonly `Ref` of a special union type: ```ts type AsyncValue = | { type: 'loading' } | { type: 'ready'; value: T } | { type: 'error'; reason: E }; ``` Works with: [`selector`](./selector.md), [`selectorFamily`](./selectorFamily.md) ```ts const useStanValueAsync: ( scopedState: | Scoped>> | Ref>>>, ) => Readonly>>; ``` :::info `useStanValueAsync` is specifically designed to work only with asynchronous state (`State>`). Failing to comply may result in unpredictable behavior or errors. ::: ### Request Example ```vue ``` ``` -------------------------------- ### useStanCallback Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Returns a callback with access to helper functions for interacting with Stan state (setting, refreshing, etc.). ```APIDOC ## `useStanCallback` Returns a callback with access to helper functions for interacting with Stan state (setting, refreshing, etc.). ```ts const useStanCallback: ( factory: (helpers: StanCallbackHelpers) => (...args: A) => R, ) => (...args: A) => R; ``` - `factory` – A curried callback function, where: - `helpers` – State helpers: - `get` – A function for getting [`State`](./state.md#statet) value, with the following signature: ```ts (scopedState: Scoped>) => T; ``` - `set` – A function for setting [`WritableState`](./state.md#writablestatet), with the following signature: ```ts ( scopedState: Scoped>, valueOrUpdater: T | ((currentValue: T) => T), ) => void ``` - `reset` – A function for [resetting](./utils.md#reset) [`WritableState`](./state.md#writablestatet), with the following signature: ```ts (scopedState: Scoped>) => void ``` - `refresh` – A function for [refreshing](./utils.md#refresh) [`ReadonlyState`](./state.md#readonlystatet), with the following signature: ```ts (scopedState: Scoped>) => void ``` :::info Unlike React's [`useStanCallback`](./react.md#usestancallback), the Vue composable takes no `deps` array. A Vue component's `setup()` runs once, so the returned callback already captures the latest values via closure. ::: ### Example ```vue ``` ``` -------------------------------- ### useStan Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/react.md Combines value access and a setter function, similar to React's useState. ```APIDOC ## `useStan` Hook ### Description Returns a tuple with a value and a setter or updater function for [`WritableState`](./state.md#writablestatet). Think of it as a combination of [`useStanValue`](#usestanvalue) and [`useSetStanValue`](#usesetstanvalue) - a Stan-specific version of React's `useState`. Works with: [`atom`](./atom.md), [`atomFamily`](./atomFamily.md) :::info `useStan` does not work with [`ReadonlyState`](./state.md#readonlystatet). ::: ### Signature ```ts const useStan: ( scopedState: Scoped>, ) => readonly [T, SetterOrUpdater]; ``` ### Example ```tsx import { atom } from "@rkrupinski/stan"; import { useStan } from "@rkrupinski/stan/react"; const myAtom = atom(42); function MyComponent() { const [value, setValue] = useStan(myAtom); return ( <>

{value}
); } ``` ``` -------------------------------- ### atomFamily API Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/atomFamily.md Reference for the atomFamily function, its parameters, options, and usage. ```APIDOC ## atomFamily ### Description `atomFamily` is used to map values to atoms based on a given parameter. It returns a memoized function that outputs atoms based on a provided, serializable parameter. ### Type Signature ```ts const atomFamily: ( initialValue: T | ValueFromParam, options?: AtomFamilyOptions, ) => (param: P) => Scoped>; ``` ### Parameters - `initialValue` (T | ValueFromParam) - The initial value for the atom. Can be a function that returns a value based on the parameter. - `options` (AtomFamilyOptions, optional) - Configuration options for the atom family: - `tag` (string | (param: P) => string, optional) - A string identifier for the atom, or a function to generate a tag based on the parameter. - `effects` (Array>, optional) - An array of atom effects. - `areValuesEqual` ((a: T, b: T) => boolean, optional) - A function to compare values for equality. ### Notes Stan does not rely on referential equality for `atomFamily` parameters. Cache keys are generated by serializing parameter values, hence the requirement for parameters to be serializable. ### Examples #### Tracking score per userId ```ts const scores = atomFamily(0); ``` #### Tracking score per User object ```ts type User = { id: string; score: number; }; const scores = atomFamily(user => user.score); ``` #### Increasing the score (React Example) ```tsx const Scoreboard: FC<{ user: User }> = ({ user }) => { const [score, setScore] = useStan(scores(user)); return ( <>

{score}

); }; ``` #### Increasing the score (Vue Example) ```vue ``` ### See Also - [`atom`](./atom.md) - [Using Stan with React](./react.md) - [Using Stan with Vue](./vue.md) ``` -------------------------------- ### Reset WritableState with useStanReset Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Wraps the `reset` utility to provide a function that resets a `WritableState`. Works with `atom` and `atomFamily`. Ensure the state is correctly imported and passed. ```typescript const useStanReset: (scopedState: Scoped> | Ref>>) => () => void; ``` ```vue ``` -------------------------------- ### Reset State Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/utils.md The `reset` function allows you to revert a WritableState to its initial value. It is compatible with atoms and atom families. ```APIDOC ## `reset` ### Description Resets the [`WritableState`](./state.md#writablestatet) to its default (initial) value. Works with: [`atom`](./atom.md), [`atomFamily`](./atomFamily.md) ### Signature ```ts const reset: (state: WritableState) => void; ``` ``` -------------------------------- ### useStan API Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/vue.md Provides a writable computed reference for WritableState, enabling two-way data binding with v-model. ```APIDOC ## `useStan` API Returns a [`WritableComputedRef`](https://vuejs.org/api/reactivity-core.html#computed) for [`WritableState`](./state.md#writablestatet). Reading `.value` subscribes to state changes; assigning to `.value` writes through to the store. Works with `v-model`. Works with: [`atom`](./atom.md), [`atomFamily`](./atomFamily.md) ```ts const useStan: (scopedState: Scoped> | Ref>>) => WritableComputedRef; ``` :::info `useStan` does not work with [`ReadonlyState`](./state.md#readonlystatet). ::: ### Request Example ```vue ``` ``` -------------------------------- ### Wrap Root Layout with StanProvider in React/Next.js Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/guides/ssr.md To scope and isolate state per request during server-side rendering in React/Next.js, wrap the root of your application with StanProvider. This ensures proper state management in SSR environments. ```tsx import { StanProvider } from '@rkrupinski/stan/react'; export default function RootLayout({ children }: { children: ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Define selectorFamily with LRU Cache and TTL Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/selectorFamily.md Defines a selectorFamily with an LRU cache policy and a Time-To-Live (TTL) of 60 seconds, automatically refreshing cached requests. ```typescript const userById = selectorFamily, string>( userId => ({ signal }) => getUser(userId, { signal }), { cachePolicy: { type: 'lru', maxSize: 5, ttl: 60_000, }, }, ); ``` -------------------------------- ### WritableState Source: https://github.com/rkrupinski/stan/blob/master/packages/website/docs/api/state.md An extension of State that allows for both reading and writing state values. It is produced by `atom` and `atomFamily`. ```APIDOC ## WritableState ### Description A state interface that can be both read from and written to. It is eagerly evaluated and produced by `atom` and `atomFamily`. ### Inherited Properties - **key** (string) - **get** (function) - **subscribe** (function) ### Additional Properties - **set** (function) - A function used to update the state value. Accepts a new value or an updater function. - **[RESET_TAG]** (function) - Resets the state to its default value and notifies subscribers. This function is intended for internal use and should typically be accessed via utility functions like `reset`. ```