Gathering detailed insights and metrics for mobx-sync-lite
Gathering detailed insights and metrics for mobx-sync-lite
Gathering detailed insights and metrics for mobx-sync-lite
Gathering detailed insights and metrics for mobx-sync-lite
npm install mobx-sync-lite
Typescript
Module System
TypeScript (99.75%)
Shell (0.25%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
2 Stars
188 Commits
1 Forks
1 Watchers
12 Branches
6 Contributors
Updated on Apr 13, 2023
Latest Version
3.1.0
Package Id
mobx-sync-lite@3.1.0
Unpacked Size
129.35 kB
Size
26.88 kB
File Count
32
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
mobx-sync-lite is a library that uses JSON to persist your MobX stores with version control. It is a fork of mobx-sync with the goal of supporting current versions of MobX.
JSON.stringify
/JSON.parse
as the deserialize/serialize method@version
decorator@ignore
decorator1# by yarn 2yarn add mobx-sync-lite 3 4# OR by npm 5npm i -S mobx-sync-lite
1import { AsyncTrunk, date } from 'mobx-sync-lite'; 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-lite instance, it will: 16// 1. load your state from localStorage & ssr rendered 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 initial 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 has been changed, which means
the persisted data is illegal to use, you can use @version
decorator
to mark the store node with a version
, if the persisted version is different
from the declared node's version, the persisted version will be ignored.
For example, we publish an application like the Quick Start at first,
and then we want to change the type of Store#foo
from string
to number
.
The persisted string value of foo
thus become illegal, and should be ignored.
It is necessary to use @version
to mark the foo
field with a new version to omit it:
1import { version } from 'mobx-sync-lite'; 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// ...
When application with the new version is executed, the persisted
value of foo
will be ignored, while date
keeps the persisted value.
It means, after calling trunk.init()
,the foo
becomes 1
,
and date
still stores the previous value.
NOTE: if the new version 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
also supports class decorator, that means any instance of the
class will be ignored if its version is different. For example:
1import { version } from 'mobx-sync-lite'; 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 version with
1
, they 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 to skip persisting, just like an article
with big size of detailed content. you can use @ignore
decorator to mark it,
those fields will not be loaded (even if it is persisted in previous version) in the initial,
and also the subsequent change will not trigger the action of persisting.
For example: if we want to ignore the date
field in Quick Start, we just need to
use @ignore
to decorate it:
1import { date, ignore } from 'mobx-sync-lite'; 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 decorating 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 a 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-lite'; 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, it will not be persisted. 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-lite maybe one.
At first, you need to call config({ ssr: true })
before call any decorator
of mobx-sync-lite. 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-lite' 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-lite'; 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-lite'; 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-lite to load SSR state, you can use
parseStore(store, state, true)
to load it.
For example:
1// client.ts 2import { parseStore } from 'mobx-sync-lite'; 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}
1The MIT License (MIT) 2 3Copyright (c) 2021 thornbill 4 5Copyright (c) 2016-2020 acrazing 6 7Permission is hereby granted, free of charge, to any person obtaining a copy 8of this software and associated documentation files (the "Software"), to deal 9in the Software without restriction, including without limitation the rights 10to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11copies of the Software, and to permit persons to whom the Software is 12furnished to do so, subject to the following conditions: 13 14The above copyright notice and this permission notice shall be included in all 15copies or substantial portions of the Software. 16 17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23SOFTWARE.
No vulnerabilities found.
No security vulnerabilities found.