npm install chain-store
sync log dedupe supersede throttle debounceAn action takes an Input and emits an Output through a chain of commands. A chain supports three types of commands:
.map transforms the value from the previous command and passes the result to the next command..filter conditionally stops execution based on the value from the previous command..task returns a Task: an asynchronous action designed for business logic.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) => {...})
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.
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"
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 */
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.
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 */
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.
<R = State>(map?: (state: State) => R, deps?: DependencyList): R
v1.xnpm 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.
<R = State>(map?: (state: State) => R): Accessor<R>
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.
<R = State>(map?: (state: State) => R, deps?: WatchSource<unknown>[]): DeepReadonly<Ref<R>>
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>
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.
<R = State>(map?: (state: State) => R): Signal<R>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 */
Call<Input, Output = void>: (input: Promise<Input> | Input) => Output
Unit<Param, Ext = void>
(fn: (param: Param, ext: Ext) => void): Disposerfn to the unit’s emitter and returns a Disposer: a void function
that removes the subscription.<Input, Output>extends Call<Input, void>
extends Unit<Output>
Emits Output when the action completes.
map:(fn: <Mapped>(param: Output) => Promise<Mapped> | Mapped): Action<Input, Mapped>
Creates a new action that transforms Output into Mapped.
filter:(fn: (param: Output) => Promise<boolean> | boolean): Action<Input, Output>
Creates a new action that filters Output. If the value is filtered out, execution and emission stop.
task:(fn: <Result>(param: Output) => Promise<Result>): Task<Input, Output, Result>
Creates a Task with the provided asynchronous command.
<Input, Params, Result>extends Call<Input, Promise<Result>>
Returns a Promise<Result> when called.
extends Unit<Param>
Emits Params when the command is called.
done:Unit<Result, Params>
Emits Result and Params when the task’s promise resolves.
fail:Unit<Error, Params>
Emits Error and Params when the task’s promise rejects.
end: Unit<Params>
Emits Params when the task’s promise settles.
<State>extends Unit<State>
Emits State when the state changes, as determined by strict equality (===).
get:() => State
Returns the current state.
set:(next: State) => void
Sets the store’s state.
on:<P, X = void>(unit: Unit<P, X>, fn: (state: State, params: P, ext: X) => State): Store<State>
Subscribes the store to a unit’s emitter. fn must return the next state. Only one subscription per unit is allowed at a time. If unit emits State, you don’t need to specify second parameter.
off:(unit: Unit): Store<State>
Unsubscribes the store from a unit.
map: (mapper: <Mapped>(state: State) => Mapped): StorePart<Mapped>
Creates a read-only store (without .on, or .set) that holds the mapped value and updates automatically when the parent store changes.
subscribe:(fn: (state: State) => void): Disposer
Like Unit.watch, but immediately invokes the callback with the current state value.
npm install @chain-store/tools
(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 });
(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 });
(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));
(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));
(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));