Palette
    Preparing search index...

    Class State<Shape>

    Powerful and flexible state management with deep reactivity, transaction, and locking support.

    The State class wraps stateful data and provides an API for mutating the data while listeners subscribe to meaningful updates.

    Modify state with setters, mutators, transactions, or proxied updates with deep reactivity and array mutation support built in.

    const state = new State({count: 1});
    state.addListener(data => console.log(data))

    state.set("count", 2); // Prints "2"
    state.set("count", 2); // Nothing happens, no change
    state.live.count = 3; // Prints "3"

    Type Parameters

    • Shape extends object
    Index

    Constructors

    Accessors

    • get current(): Readonly<Shape>

      The current state

      Returns Readonly<Shape>

      This is a direct reference to the internal state. It is marked as Readonly to help prevent accidental changes. Never edit this value directly.

    • get isLocked(): boolean

      Indicates if this state is currently locked (true) or not (false)

      Returns boolean

    • get live(): Shape

      Proxied access to state properties with automatic reconciliation.

      Allows direct property access for both reading and writing state values.

      Returns Shape

      Deep reactivity with the .live accessor

      const state = new State({
      nested: {
      values: [1, 2, 3],
      }
      });

      // Deep value assignment triggers state updates
      state.live.nested.values[1] = 5;

      // Array mutators are automatically reactive as well
      state.live.nested.values.push(4);
      state.live.nested.values.reverse();

    Methods

    • Add a handler function for when this state changes.

      Listeners are invoked in the order they are registered and are passed a reference to the internally managed state object as a readonly object.

      Do not modify state values directly. Instead, use set or patch to make immutable updates.

      Parameters

      Returns void

    • Get a single value from the state object

      The value is returned as Readonly to prevent accidental state mutations. To mutate stateful properties, use set or patch instead.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      • key: K

      Returns Readonly<Shape[K]>

      const state = new State({ count: 1 });
      console.log(state.get("count")); // 1
    • Lock this State instance, preventing further external changes

      Returns State<Shape>

    • Apply complex updates to the state using a mutator function.

      The mutator function takes one parameter which is a structuredClone copy of the current state object. Whatever is returned by the mutator is then patched in to the state.

      Parameters

      Returns State<Shape>

    • Perform an async mutation of the state, optionally locking the state during the process.

      Parameters

      • mutator: (current: Shape) => Promise<Shape>

        A function to mutate and return the new state

      • lock: boolean = false

        If true, lock the state until the mutator completes

      Returns Promise<State<Shape>>

    • Set multiple stateful properties at once, leaving omitted properties unchanged.

      Parameters

      Returns State<Shape>

      Patch a partial state, updating all listed properties at once

      const state = new State({
      weather: "sunny",
      temperature: 30,
      humidity: 70,
      });

      // Leaves `temperature` unchanged
      state.patch({
      weather: "cloudy",
      humidity: 50,
      });
    • Remove a previously registered state handler

      Parameters

      Returns void

    • Fully replace the current state data and force listeners to receive the updated data immediately.

      Parameters

      Returns State<Shape>

    • Set a single stateful property while leaving other properties unchanged.

      Triggers an update to all listeners if the value is different from before when compared using shallow equality.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      Returns void

      const state = new State({ count: 1, color: "red" });
      state.set("count", 2); // State is now { count: 2, color: "red" }
    • Returns a deep clone of the current state data using structuredClone() to make the copy.

      The object returned from this function can be edited without modifying the actual internal state.

      Returns Shape

      const snap = state.snapshot();
      snap.count += 1;
      state.patch(snap);
    • Perform a transaction-style set of actions defined within a function.

      The provided function can do anything, beyond just setting state. Any uncaught errors thrown from within the function will cause the transaction to fail and the state to automatically roll back to the last valid state.

      During a transaction, this state instance will be locked, preventing other changes.

      Transactions will always result in a state update when successful.

      Parameters

      Returns boolean

      Transactions with locking and rollback support

      const state = new State({count: 1});

      state.transaction(async (s) => {
      // `s` is a full State object you can safely manipulate
      s.set("count", 10);
      });
      state.get("count"); // => 10;

      // Errors inside the transaction roll back the state
      state.transaction(async (s) => {
      s.set("count", 100);
      throw new Error();
      });
      state.get("count");
    • Perform a transaction-style set of actions defined within an async function

      The provided function can do anything, beyond just setting state. Any uncaught errors thrown from within the function will cause the transaction to fail and the state to automatically roll back to the last valid state.

      During a transaction, this state instance will be locked, preventing other changes.

      Transactions will always result in a state update when successful.

      Parameters

      Returns Promise<boolean>

      Transactions with locking and rollback support

      const state = new State({count: 1});

      // Awaiting the result of a transaction
      await state.transactionAsync(async (s) => {
      // `s` is a full State object you can safely manipulate
      s.set("count", 10);
      });
      state.get("count"); // => 10;

      // Errors inside the transaction roll back the state
      await state.transactionAsync(async (s) => {
      s.set("count", 100);
      throw new Error();
      });
      state.get("count"); // => 10;

      // If you forget to await the transaction, its still locked
      state.transactionAsync(async (s) => {
      await waitSeconds(1);
      });
      state.set("count", 1); // Error: State is locked!
    • Unlock this State instance, allowing further external changes

      Returns State<Shape>