Gathering detailed insights and metrics for mobx-sync
Gathering detailed insights and metrics for mobx-sync
Gathering detailed insights and metrics for mobx-sync
Gathering detailed insights and metrics for mobx-sync
mobx-react-router
Keep your MobX state in sync with react-router
mobx-url-sync
Synchronizes MobX observables with URL query parameters.
@superwf/mobx-react-router
Keep your MobX state in sync with react-router
mobx-sync-storage
Sync persist storage between Local/Session Storage and MobX
npm install mobx-sync
Typescript
Module System
Node Version
NPM Version
TypeScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
148 Stars
57 Commits
11 Forks
1 Watchers
16 Branches
5 Contributors
Updated on Aug 31, 2024
Latest Version
3.0.0
Package Id
mobx-sync@3.0.0
Unpacked Size
129.36 kB
Size
21.53 kB
File Count
31
NPM Version
6.14.5
Node Version
12.16.1
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
A library use JSON to persist your mobx stores with version control.
JSON.stringify/JSON.parse
as the deserialize/serialize method@version
decorator@ignore
decorator1# by yarn 2yarn add mobx-sync 3 4# OR by npm 5npm i -S mobx-sync
1import { AsyncTrunk, date } from 'mobx-sync'; 2import { observable } from 'mobx'; 3 4class Store { 5 @observable 6 foo = 'bar'; 7 8 @date 9 @observable 10 date = new Date(); 11} 12 13const store = new Store(); 14 15// create a mobx-sync instance, it will: 16// 1. load your state from localStorage & ssr renderred state 17// 2. persist your store to localStorage automatically 18// NOTE: you do not need to call `trunk.updateStore` to persist 19// your store, it is persisted automatically! 20const trunk = new AsyncTrunk(store, { storage: localStorage }); 21 22// init the state and auto persist watcher(use mobx's autorun) 23// NOTE: it will load the persisted state first(and must), and 24// then load the state from ssr, if you pass it as the first 25// argument of `init`, just like trunk.init(__INITIAL_STATE__) 26trunk.init().then(() => { 27 // you can do any staff now, just like: 28 29 // 1. render app with inited state: 30 ReactDOM.render(<App store={store} />); 31 32 // 2. update store, the update of the store will be persisted 33 // automatically: 34 store.foo = 'foo bar'; 35});
You can see it at example
Sometimes, if your store's data structure is changed, which means
the persisted data is illegal to use, you can use @version
decorator
to mark the store node's version
, if the persisted data's version is
different with the declared node's verson, it will be ignored.
For example, we published an application like it in Quick Start,
and then we want to change the type of Store#foo
from string
to number
,
so, the persisted string value of foo
is illegal, and should be ignored, and
then, we can use @version
to mark the foo
field to new version to omit it:
1import { version } from 'mobx-sync'; 2import { observable } from 'mobx'; 3 4class Store { 5 @version(1) 6 @observable 7 foo = 1; 8 9 @date 10 @observable 11 date = new Date(); 12} 13 14// ...
If you run the new verson of the application, it will omit the persisted
value of foo
, and keep the value of date
, so, after call trunk.init()
,
the foo
will be 1
, and date
will be previous verson's value.
NOTE: if the new verson is strictly different with the persisted version, it will be ignored, or else it will be loaded as normal, so if you use it, we recommend you use an progressive increasing integer to mark it, because you couldn't know the version of persisted in client.
@version
supports decorate class also, that means if any instance of the
class will be ignored if its verson is different. For example:
1import { version } from 'mobx-sync'; 2import { observable } from 'mobx'; 3 4@version(1) 5class C1 { 6 p1 = 1; 7} 8 9class C2 { 10 p2 = 2; 11} 12 13class Store { 14 c1 = new C1(); 15 c2 = new C2(); 16 c1_1 = new C1(); 17}
If the persisted version of store's c1
&& c1_1
has different verson with
1
, it will be ignored.
NOTE: if you use a non-pure object as the store field, you must initialize it
before you call trunk.init
, just like custom store class
(C1
, C2
upon),
observable.map
, observable.array
, etc. And it must be iterable by for..in
grammar, if not, you may need to use a custom formatter(see
custom formatter bellow) to serialize/de-serialize it.
Signature:
1function version(id: number): PropertyDecorator & ClassDecorator;
If you hope some fields of your store is ignored to persist, just like the artile
with big size of detailed content. you can use @ignore
decorator to mark it as
ignored, it will not be loaded (even if it is persisted in previous version) when
init, and its change will not trigger the persist action.
For example: if we want to skip the date
field in Quick Start, we just need to
use @ignore
to decorate it:
1import { date, ignore } from 'mobx-sync'; 2import { observable } from 'mobx'; 3 4class Store { 5 @observable 6 foo = 'bar'; 7 8 @ignore 9 @date 10 @observable 11 date = new Date(); 12}
@ignore
only supports decorate property.
Signature:
1/** 2 * works in web environment only 3 */ 4function ignore(target: any, key: string): void; 5namespace ignore { 6 /** 7 * works in both web and ssr environment 8 */ 9 function ssr(target: any, key: string): void; 10 11 /** 12 * works in ssr environment only 13 */ 14 function ssrOnly(target: any, key: string): void; 15}
Sometimes, your store node is not pure object, just like Set
, Map
,
observable.map<number, Date>
, etc, you may need to use custom formatter
(@format
) to parse/stringify the data/value.
For example, we use Set<Date>
as a field:
1import { format } from 'mobx-sync'; 2import { observable } from 'mobx'; 3 4class Store { 5 @format( 6 (data: string[]) => new Set(data.map((d) => new Date(d))), 7 (value: Set<Date>) => Array.from(value, (v) => v.toISOString()), 8 ) 9 @observable 10 allowDates = new Set<Date>(); 11}
Built-in formatters:
@date
: parse/stringify date@regexp
: parse/stringify regexpSignature:
1/** 2 * define a custom stringify/parse function for a field, it is useful for 3 * builtin objects, just like Date, TypedArray, etc. 4 * 5 * @example 6 * 7 * // this example shows how to format a date to timestamp, 8 * // and load it from serialized string, 9 * // if the date is invalid, will not persist it. 10 * class SomeStore { 11 * @format<Date, number>( 12 * (timestamp) => new Date(timestamp), 13 * (date) => date ? +date : void 0, 14 * ) 15 * dateField = new Date() 16 * } 17 * 18 * @param deserializer - the function to parse the serialized data to 19 * custom object, the first argument is the data serialized by 20 * `serializer`, and the second is the current value of the field. 21 * @param serializer - the function to serialize the object to pure js 22 * object or any else could be stringify safely by `JSON.stringify`. 23 */ 24function format<I, O = I>( 25 deserializer: (persistedValue: O, currentValue: I) => I, 26 serializer?: (value: I) => O, 27): PropertyDecorator; 28 29function date(target: any, key: string): void; 30 31function regexp(target: any, key: string): void;
Sometimes, we hope to use mobx in SSR(Server-Side Rendering), there is no standard way to stringify/load mobx store to/from html template, mobx-sync maybe one.
At first, you need to call config({ ssr: true })
before call any decorator
of mobx-sync. And then, you can use JSON.stringify
to stringify your state
to html template, and then use trunk.init
or parseStore
to load it to
your store.
For example:
1// store.ts 2import { ignore } from 'mobx-sync' 3import { observable } from 'mobx' 4 5export Store { 6 @observable userId = 0 7 8 @ignore.ssr 9 users = observable.map() 10}
1// server.ts 2import { config } from 'mobx-sync'; 3 4config({ ssr: true }); 5 6import { Store } from './store'; 7 8app.get('/', (_, res) => { 9 const store = new Store(); 10 11 res.end(`<!DOCTYPE html> 12 <html> 13 <body> 14 <div id=root>${renderToString(<App store={store} />)}</div> 15 <script>var __INITIAL_STATE__ = ${JSON.stringify(store).replace( 16 /</g, 17 '\\u003c', 18 )}</script> 19 </body> 20 </html>`); 21});
1// client.ts 2import { AsyncTrunk } from 'mobx-sync'; 3import { Store } from './store'; 4 5const store = new Store(); 6const trunk = new AsyncTrunk(store); 7 8trunk.init(__INITIAL_STATE__).then(() => { 9 ReactDOM.render(<App store={store} />, document.querySelector('#root')); 10});
NOTE: if you do not want to use a trunk to persist/load state from
localStorage, just want to use mobx-sync to load SSR state, you can use
parseStore(store, state, true)
to load it.
For example:
1// client.ts 2import { parseStore } from 'mobx-sync'; 3import { Store } from './store'; 4 5const store = new Store(); 6 7parseStore(store, __INITIAL_STATE__, true); 8 9ReactDOM.render(<App />, document.querySelector('#root'));
Signature:
1interface Options { 2 ssr: boolean; 3} 4 5function config(options: Partial<Options>): void; 6 7function parseStore(store: any, data: any, isFromServer: boolean): void;
Both of AsyncTrunk
and SyncTrunk
is the class to auto load/persist
store to storage, the difference between them is the AsyncTrunk
runs
asynchronously and SyncTrunk
runs synchronously.
Signature:
1// this is a subset of `Storage` 2interface SyncStorage { 3 getItem(key: string): string | null; 4 setItem(key: string, value: string): void; 5 removeItem(key: string): void; 6} 7 8// this is a subset of `ReactNative.AsyncStorage` 9interface AsyncStorage { 10 getItem(key: string): Promise<string | null>; 11 setItem(key: string, value: string): Promise<void>; 12 removeItem(key: string): Promise<void>; 13} 14 15/** 16 * sync trunk initial options 17 */ 18export interface SyncTrunkOptions { 19 /** 20 * storage, SyncStorage only 21 * default is localStorage 22 */ 23 storage?: SyncStorage; 24 /** 25 * the storage key, default is KeyDefaultKey 26 */ 27 storageKey?: string; 28 /** 29 * the delay time, default is 0 30 */ 31 delay?: number; 32 33 /** 34 * error callback 35 * @param error 36 */ 37 onError?: (error: any) => void; 38} 39 40/** 41 * the async trunk initial options 42 */ 43export interface AsyncTrunkOptions { 44 /** 45 * storage, both AsyncStorage and SyncStorage is supported, 46 * default is localStorage 47 */ 48 storage?: AsyncStorage | SyncStorage; 49 /** 50 * the custom persisted key in storage, 51 * default is KeyDefaultKey 52 */ 53 storageKey?: string; 54 /** 55 * delay milliseconds for run the reaction for mobx, 56 * default is 0 57 */ 58 delay?: number; 59 60 /** 61 * error callback 62 * @param error 63 */ 64 onError?: (error: any) => void; 65} 66 67class AsyncTrunk { 68 disposer: () => void; 69 constructor(store: any, options?: AsyncTrunkOptions); 70 init(initialState?: any): Promise<void>; 71 // call persist manually 72 persist(): Promise<void>; 73 // clear persisted state in storage 74 clear(): Promise<void>; 75 // change the store instance 76 updateStore(): Promise<void>; 77} 78 79class SyncTrunk { 80 disposer: () => void; 81 constructor(store: any, options?: SyncTrunkOptions); 82 init(initialState?: any): void; 83 // call persist manually 84 persist(): void; 85 // clear persisted state in storage 86 clear(): void; 87 // change the store instance 88 updateStore(): void; 89}
The MIT License (MIT)
Copyright (c) 2016 acrazing
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 4/24 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
32 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More