Skip to content

Repository files navigation

@js-toolkit/mobx-utils

npm packagelicense

MobX utilities: store management with createStore / createRootStore, serialization, LocalForage-based state persistence, and JWT helpers.

Install

yarn add @js-toolkit/mobx-utils
# or
npm install @js-toolkit/mobx-utils

Requires mobx as a peer dependency.

Import

import{createStore,createRootStore,attachSelectors}from'@js-toolkit/mobx-utils/store/object';import{serialize}from'@js-toolkit/mobx-utils/serialization/serialize';

API Overview

Store Management (store/object)

ExportDescription
createStoreCreate a MobX store with init, update, reset, getSnapshot
createRootStoreCreate a root store that manages child stores
attachSelectorsAttach computed selectors to a root store
updateStateUpdate store state with a patch
getSnapshotGet a plain JS snapshot of store state
isStore, isRootStoreType guards

Serialization (serialization/serialize)

ExportDescription
serializeRecursively serialize objects (handles dates, Option, custom serializers)

Storage (storage)

ExportDescription
saveStoreStateSave a single store state to LocalForage
saveRootStateSave multiple stores to LocalForage
getStoreStateRetrieve store state from LocalForage (returns Option)

Auth (auth)

ExportDescription
decodeTokenDecode JWT token (returns Option)
isExpiredCheck if JWT token is expired

Utilities

ExportDescription
hasInType-safe wrapper around MobX has
isArrayType guard for arrays (including MobX observable arrays)

Usage Examples

Create stores

import{observable}from'mobx';import{createStore,createRootStore,attachSelectors}from'@js-toolkit/mobx-utils/store/object';constroot=createRootStore({auth: createStore({token: '',username: '',}),ui: createStore({theme: 'light'as'light'|'dark',items: []asstring[],},{items: observable.shallow,}),});conststore=attachSelectors(root,{getisLoggedIn(): boolean{returnroot.auth.token.length>0;},});store.auth.update({token: 'abc123'});console.log(store.isLoggedIn);// truestore.auth.reset();

Serialize store state

import{serialize}from'@js-toolkit/mobx-utils/serialization/serialize';constsnapshot=serialize(store.auth);

Persist and restore state

import{saveStoreState,getStoreState}from'@js-toolkit/mobx-utils/storage';awaitsaveStoreState<typeofroot>('auth',root.auth);constsaved=awaitgetStoreState<typeofroot>('auth');if(saved.nonEmpty()){root.auth.update(saved.get());}

JWT helpers

import{decodeToken}from'@js-toolkit/mobx-utils/auth/decodeToken';import{isExpired}from'@js-toolkit/mobx-utils/auth/isExpired';constdecoded=decodeToken(token);if(decoded.nonEmpty()&&!isExpired(decoded.get())){// token is valid}

Repository

https://github.com/vlazh/mobx-utils

About

Base classes and utilities of mobx stores and validable mobx models.

Topics

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages