tiny-state-store
Small and super simple general purpose state store. Runs in node and the browser, written in TypeScript.
- Installation
- Basic usage
- Reacting on state changes
- Example merge fn: special update data structure
- Example merge fn: deep merging updates
- API reference
Installation
npm i tiny-state-store
Basic usage
The basics of the lib are getState
and setState
. By default setState
will do a shallow merge of the current state and the state update. In case you need a different merge strategy you can write a custom merge function.
; ; ;; store.setState;console.logstore.getState;
Reacting on state changes
You can pass an onChange handler that will get called whenever the state object changes. State change is determined by a single ===
check on the root state object.
; ; ;; store.setState;
Example merge fn: special update data structure
By default setState
takes partial state updates, but by you can customize what structures setState
understands by using a custom merge function:
; ;; ;;; store.setState;
Example merge fn: deep merging updates
By default the lib only does a shallow copy of the state updates, because implementing deep merge requires to make choices that are best made on application level. Example:
;; ; ; ; ; ; store.setState;
API reference
createStore<State, StateUpdate = Partial<State>>(initialState: State, onChange?: OnChangeFn<State>, mergeFn?: MergeFn<State, StateUpdate>): Store<State>
Creates new store with initial state. Takes optional parameters:
onChange?: (state: State, prevState: State) => void
: function called when the state object changedmergeFn?: (a: State, b: StateUpdate): State
. Can be used to override the default shallow merge function. When the returned state object does not equal the current object (===
) onChange will be triggered.
store.getState(): State
Returns current state. WARNING: returned object is the actual current state object, immutability is not enforced.
store.setState(update: StateUpdate): void
Sets partial state update and triggers "onChange" determined by a single ===
check on the root state object.