mst-persist
Persist and hydrate MobX-state-tree stores.
Installation
npm i -S mst-persist
Usage
import { types } from 'mobx-state-tree'
import localForage from 'localForage'
import { persist } from 'mst-persist'
const SomeStore = types.model('Store', {
name: 'John Doe',
age: 32
})
const someStore = SomeStore.create()
persist('some', someStore, {
storage: localForage, // or AsyncStorage in react-native.
// default: localStorage
jsonify: false // if you use AsyncStorage, this shoud be true
// default: true
whitelist: ['name'] // only these keys will be persisted
}).then(() => console.log('someStore has been hydrated'))
API
persist(key, store, options)
- arguments
- **storage** *[localForage](https://github.com/localForage/localForage) / [AsyncStorage](https://github.com/react-native-community/async-storage) / [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)*
Any Storage Engine that has a Promise-style API similar to [`localForage`](https://github.com/localForage/localForage).
The default is [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage), which has a built-in adaptor to make it support Promises.
For React Native, one may configure [`AsyncStorage`](https://github.com/react-native-community/async-storage) instead.
<br>
Any of [`redux-persist`'s Storage Engines](https://github.com/rt2zz/redux-persist#storage-engines) should also be compatible with `mst-persist`.
- **jsonify** *bool* Enables serialization as JSON (default: `true`).
- **whitelist** *Array\<string\>* Only these keys will be persisted (defaults to all keys).
- **blacklist** *Array\<string\>* These keys will not be persisted (defaults to all keys).
- returns a void Promise
Node and Server-Side Rendering (SSR) Usage
Node environments are supported so long as you configure a Storage Engine that supports Node, such asredux-persist-node-storage
, redux-persist-cookie-storage
, etc.
This allows you to hydrate your store server-side.For SSR though, you may not want to hydrate your store server-side, so in that case you can call
persist
conditionally:if (typeof window !== 'undefined') { // window is undefined in Node
persist(...)
}
With this conditional check, your store will only be hydrated client-side.
Examples
None yet, but can take a look at agilgur5/react-native-manga-reader-app which uses it in production. Can view the commit that implements it here.How it works
Basically just a small wrapper around MST'sonSnapshot
and applySnapshot
.
The source code is currently shorter than this README, so take a look under the hood! :)Credits
Inspiration for parts of the code and API came fromredux-persist
, mobx-persist
, and this MST persist PoC gist