@chain-store/react
v0.1.0
Published
React adapter for chain-store, a tiny yet surprisingly powerful event-based state manager.
Maintainers
Readme
@chain-store/react
React adapter for chain-store, a tiny yet surprisingly powerful event-based state manager.
- Actions with pre-bound chains of filters and mappings;
- Asynchronous tasks for business logic;
- Independent stores that can be watched in full or in part;
- Customizable synchronization between stores, actions, and tasks;
- Small and dependency-free: 938 bytes minified & brotlied with the React adapter included.
- Tools to sync stores across tabs and log state changes to Redux DevTools.
npm install chain-store @chain-store/react// store.ts
import { chain, store, type Action, type Task } from "@chain-store/react";
export type State = { page: number; data: Record<number, string[]> };
export const $store = store({ page: 1, data: {} });
export const action: Action<number | void, number> = chain<number | void>()
.map((shift: number | void) => $store.get().page + (shift ?? 0))
.filter((page: number) => page >= 1);
export const task: Task<number | void, number, string[]> = action.task(
(page: number): Promise<string[]> =>
fetch(`/data?page=${page}`).then((result) => result.json()),
);
$store
.on(action, (state: State, page: number) => ({ ...state, page }))
.on(task.done, (state: State, data: string[], page: number) => {
state.data[page] = data; /* Supports mutations */
return state;
});// app.tsx
import React, { useEffect } from "react";
import { $store, action, type State } from "./store";
export const App = () => {
const page: number = $store.use().page;
const data: string[] = $store.use(
(state: State) => state.data[page] ?? [],
[page],
);
useEffect(() => {
action();
}, []);
return (
<>
<button onClick={() => action(-1)}>Previous</button>
<strong>Page: #{page}</strong>
<button onClick={() => action(1)}>Next</button>
<ul>
{data.map((item, key) => <li key={key}>{item}</li>)}
</ul>
</>
);
};