chain-store

Event-based state manager.
Tiny in size. Big on capabilities.

Installation

npm install chain-store

Table of contents:


Action

An action takes an Input and emits an Output through a chain of commands. A chain supports three types of commands:

import { chain, type Action, type Task } from "chain-store";

/** Create an action */
const testAction: Action<number, string> = chain<number>()
  .filter((page: number) => page >= 1)
  .map((page: number) => page.toString())


Subscribe to Action emitted outputs with .watch method. It takes callback (value: Output) => void and returns Disposer, a void function to cancel subscription.

/** Subscribe to action emitted outputs */
const dispose = testAction.watch(console.log);

/** Call the action */
testAction(1);                            //=> "1"
testAction(0);                            /* no output, 
                                             negative value is filtered out */
/** Stop watching */
dispose();


You can split a chain into separate actions as needed. Calling any action in the chain causes the other actions to emit their respective outputs.

import { chain, type Action } from "chain-store";

const number: Action<number, number> = chain<number>();
const double: Action<number, number> = number.map(n => n * 2);
const string: Action<number, string> = number.map(n => n.toString());

double.watch((value) => console.log("double", value));
string.watch((value) => console.log("string", value));

number(42);                               //=> "double", 84
                                          //=> "string", "42"

/** It doesn't matter which action in the chain you call */
double(-1);                               //=> "double", -2
                                          //=> "string", "-2"


A chain can include asynchronous commands. It waits for each promise to resolve before passing its result down the chain. Any rejection or thrown error stops execution.

const action = chain<number>()
  .map(async (n: number) => n.toString())
  .filter((s: string) => s.length > 1);

action.watch((result: string) => {...})


Task

Tasks are the logical endpoints of chains and are designed for business logic. When called, a task emits its input parameters. It also emits a success or failure event when the operation resolves or rejects, much like a promise. Tasks are always asynchronous, even when given a synchronous command.

Create a task by adding the .task command to an action chain.

import { chain, type Task } from "chain-store";

type Result = { data: string };

const task: Task<string, string, Result> = chain<string>()
  .map((str: string) => str.toUpperCase())
  .task((str: string) => ({ data: str }));

task.watch((params: string) =>
  console.log("task", params)
);
task.done.watch((result: Result, params: string) =>
  console.log("task.done", result, params)
);
task.fail.watch((error: Error, params: string) =>
  console.log("task.fail", params, error)
);
task.end.watch((params: string) =>
  console.log("task.end", params)
);

task("test");                             //=> "task", "TEST"

//=> "task.done", { data: "TEST" }, "TEST"
//=> "task.end", "TEST"

If a task command returns the same (===) promise that is already pending within the task, the emission is skipped to avoid unnecessary store updates. If a chain is blocked or an error is thrown before the task runs, no fail event is emitted.


Task call

Each call to a task returns a Promise<Result> that represents the current task execution. This is useful for accessing the task’s result outside the store or running code when the task resolves.

const getUsers = chain<number>().task(page => `/users/page?=${page}`);

getUsers(1).then(() => {
  ...
})

Unlike emission, which stops when filtered out, the promise returned by a task call rejects with ChainFilter error.

const filter = chain<number>()
  .filter(n => n > 0)
  .task(...);

task(0)
  .catch((err) => console.log(err.name)); //=> "ChainFilter"


Store

Stores are small and granular. They can hold any type of data—objects, arrays, functions, or anything else. No changes happen behind the scenes; you control all updates.

import { store } from "chain-store";

type State = { data: string };
const $store = store<State>({ data: "init" });

$store.watch((state: State) => {
  console.log(state.data)
});

$store.set({ data: "test1" });            //=> "test1"


A store also have .subscription method differs from .watch only by immediate invoking subscription callback with current state value.

const dispose = $store.subscribe((state: State) => {
  console.log(state.data)                //=> "init"
});

dispose();


A store can be updated by actions, tasks, or other stores with .on/.off methods.

type Data = { name: string };

const $data = store<Data>({ name: "chain" });
const $state = store<{ data: Data }>({ data: $data.get() });

/*
  Update one store from another.
  
  Alternatively:
  $data.watch(data => $state.set({ ...$state.get(), data }));
*/
$state.on($data, (state, data) => {
  return { ...state, data };
});

/** Update the store from a task */
const task = chain<string>().task(
  (name: string) => ({ name: name.toUpperCase() })
);

$data
  .on(task, (state: Data, name: string) => ({ ...state, name }))
  .on(task.done, (_, result: Data) => result);

$state.watch(state => {
  console.log(state.data.name);
});

$data.set({ name: "store" });             //=> "store"

task("test");                             //=> "test"
                                          // => "TEST"

/** Unsubscribe */
$state.off($data);
$data.off(); /* Removes all subscriptions */

Partial store

Use .map on a store to get part of its state. Partial stores are read-only and cannot be updated directly.

const $store = store({ data: { name: "part" } });
const $partial = $store.map(state => state.data);

console.log($partial.get());              //=> { name: "part" }

$partial.watch((part: { name: string }) => {
  console.log(part.name);
});

$store.set({ data: { name: "test" } });   //=> "test"
$store.set({ data: $partial.get() });     /* No output: the partial state hasn't changed */

Before nullifying a partial store, make sure to call its .off() method to dispose of its subscriptions.


Optional mutability

Stores let you mutate state within updater callbacks while notifying watchers only when the watched value changes. Changes are detected using strict equality (===).

import { chain, store } from "chain-store";

type Data = { name: string };

const setUser = chain<Data>();
const setName = chain<string>();

const $store = store<Data>({ name: "chain" });

$store
  .on(setUser, (_, data: Data) => data)
  .on(setName, (state: Data, name: string) => {
    state.name = name;                    /* Mutate the state */
    return state;                         /* A return value is still required */
  });

$store.watch(data => console.log("data changed"));
$store.map(user => user.name).watch(() => console.log("name changed"));

setUser({ name: "store" });               //=> "data changed"
                                          //=> "name changed"

setName("test");                          //=> "name changed"

setUser({ name: "test" });                //=> "data changed"

setUser($store.get());                    /* No output: nothing changed */


Adapters

React v16.8+ / Preact v10+

npm install chain-store @chain-store/react

npm install chain-store @chain-store/preact

React and Preact adapters re-export the core API and types extending store with .use() hook.

import { chain, store, type Store } from "@chain-store/react";

/* Store */
const $counter: Store<number> = store({ count: 0 });

const change = chain<"plus" | "minus">()
  .map(val => val === "plus" ? 1 : -1)
  .map((val: number) => $counter.get().count + val)
  .filter((count: number) => count >= 0);

$counter.on(change, (state, count: number) => {
  return {...state, count }
});

/* App */
const App = () => {
  const count = $counter.use(state => state.count);

  return <>
    <button onClick={() => change("minus")}>Decrement</button>
    <strong>Counter: {count}</strong>
    <button onClick={() => change("plus")}>Increment</button>
  </>;
};

The use hook accepts two optional arguments: a state mapper and a dependency array to control subscription.


Solid v1.x

npm install chain-store @chain-store/solid

Solid adapter re-export the core API and types extending store with .use() hook.

import { chain, store, type Store } from "@chain-store/solid";

/* Store */
const $counter: Store<number> = store({ count: 0 });

const change = chain<"plus" | "minus">()
  .map(val => val === "plus" ? 1 : -1)
  .map((val: number) => $counter.get().count + val)
  .filter((count: number) => count >= 0);

$counter.on(change, (state, count: number) => {
  return {...state, count }
});

/* App */
const App = () => {
  const count = $counter.use(state => state.count)

  return <>
    <button onClick={() => change("minus")}>Decrement</button>
    <strong>Counter: {count()}</strong>
    <button onClick={() => change("plus")}>Increment</button>
  </>;
};

The use hook accepts optional state mapper.


Vue v3.3+

npm install chain-store @chain-store/vue

Vue adapter re-export the core API and types extending store with .use() hook.

<script lang="ts">
  import { chain, store, type Store } from "@chain-store/vue";

  /* Store */
  const $counter: Store<number> = store({ count: 0 });

  const change = chain<"plus" | "minus">()
    .map(val => val === "plus" ? 1 : -1)
    .map((val: number) => $counter.get().count + val)
    .filter((count: number) => count >= 0);

  $counter.on(change, (state, count: number) => {
    return {...state, count }
  });
</script>

<script setup lang="ts">
  const count = $counter.use(state => state.count);
</script>

<template>
  <button :click="() => change('minus')">Decrement</button>
  <strong>Counter: 8</strong>
  <button :click="() => change('plus')">Increment</button>
</template>

The use hook accepts two optional arguments: a state mapper and a dependency array to control subscription.


Svelte v4+

Svelte works out of the box because chain-store implements Svelte’s store contract.

<script lang="ts">
  import { store, chain } from "chain-store";
  
  const counter: Store<number> = store({ count: 0 });

  const change = chain<"plus" | "minus">()
    .map(val => val === "plus" ? 1 : -1)
    .map((val: number) => counter.get().count + val)
    .filter((count: number) => count >= 0);
  
  counter.on(change, (state, count: number) => {
    return {...state, count }
  });
  
  const count = counter.map(state => state.count);
</script>

<button onclick={() => change("plus")}>Increment</button>
<strong>Counter: {$count}</strong>
<button onclick={() => change("minus")}>Decrement</button>

Angular v16+

npm install chain-store @chain-store/angular

Angular adapter re-export the core API and types extending store with .use() hook.

import { chain, store, type Store } from "@chain-store/angular";
import { Component } from "@angular/core";
import { CommonModule } from "@angular/common";

/* Store */
const $counter: Store<number> = store({ count: 0 });

const change = chain<"plus" | "minus">()
  .map(val => val === "plus" ? 1 : -1)
  .map((val: number) => $counter.get().count + val)
  .filter((count: number) => count >= 0);

$counter.on(change, (state, count: number) => {
  return {...state, count }
});

/* App */
@Component({
  selector: "app-root",
  standalone: true,
  template: `
    <button (click)="decrement()">Decrement</button>
    <strong>Counter: 8</strong>
    <button (click)="increment()">Increment</button>
  `,
})

export class AppComponent {
  readonly count = $counter.use((state) => state.count);

  decrement(): void {
    change("minus");
  }

  increment(): void {
    change("plus");
  }
}

The use hook accepts optional state mapper.


Chain life cycle

Every chain has a queue of commands. Each .map or .filter call adds a command to the queue. Actions with fewer commands run earlier.

const act1 = chain();                     // 0 commands 
const act2 = act1.map().map();            // 2 commands 
const act3 = act1.map()                   // 1 command 
const task1 = act3.task()                 // 2 commands 
const act4 = act2.map()                   // 3 commands 

/* act1 -> act3 -> act2 -> task1 -> act4 -> task1.done -> task1.end */

A command emits its output before passing it down the chain. As a result, all watchers are notified before the next command runs.

const act1 = chain<number>();
const $store = store<number>(0).on(act1, (_, n) => n);

const act2 = act1.map(() => $store.get());  /* returns act1 output value */


Types summary

Call<Input, Output = void>: (input: Promise<Input> | Input) => Output


Unit<Param, Ext = void>


Action<Input, Output>


Task<Input, Params, Result>


Store<State>


Tools

npm install @chain-store/tools

sync(stores, match?, compare?, scope?)

Synchronizes stores across browser tabs using BroadcastChannel.

import { sync } from "@chains-store/tools";

const $name = store("Ada");
const $items = store([]);

sync({ $name, $items });

Full specs


log(stores, units, scope?)

Logs chain emissions and store updates to Redux DevTools.

import { log } from "@chain-store/tools";

const action = chain();
const $store = store().on(action);

log({ $store }, { action });

Full specs


dedupe(request, compare?)

Deduplicates in-flight requests made by .task.

import { dedupe } from "@chain-store/tools";
import { request } from "./api";

const deduped = chain<number>().task(dedupe(request));

Full specs


supersede(request)

Supersedes any previous in-flight request made by .task.

import { supersede } from "@chain-store/tools";
import { request } from "./api";

const superseded = chain<number>().task(supersede(request));

Full specs


throttle/debounce(delay, command)

Throttles or debounces chain command functions.

import { throttle, debounce } from "@chain-store/tools";

const action = chain<number>();
const throttled = action.map(throttle(200, (n) => n * 2));
const debounced = action.map(debounce(200, (n) => n * 2));

Full specs