Mobx State Tree Persistant Store Provider Component and Consumer Hook writen in TypeScript
npm install mst-persistent-storeA factory to easily create Persistent Mobx State Tree Store Provider and consumer hook.
- Installation
- For React
- For React Native
- Usage
- Create Provider and Hooks
- Add Provider to The Root Component
- Use the Store from Child Components
- Custom Storage Backend
- API
- createPersistentStore
- Type Definition
- Arguments
- PersistentStoreOptions
- Notes
- disallowList
- License
- Contribution
yarn add mst-persistent-store
@react-native-async-storage/async-storage and localforage are optional peer dependencies. You can use any storage you want by passing the storage object to the factory. But if you want to use the default storage, you need to install one of them. See Usage and Custom Storage Backend for more info about how to use default or custom storage.
yarn add mobx-state-tree localforage
yarn add mobx-state-tree @react-native-async-storage/async-storage
Usage is very simple.
Below is an example on how to create the provider and consumer hook.
``ts
// store-setup.ts
import { types } from 'mobx-state-tree';
import createPersistentStore from 'mst-persistent-store';
import defaultStorage from 'mst-persistent-store/dist/storage';
const PersistentStore = types
.model('RootStore', {
name: types.string,
age: types.number,
premium: types.boolean,
hydrated: types.boolean,
})
.actions((self) => ({
hydrate() {
self.hydrated = true;
},
}))
.views((self) => ({
get isAdult() {
return self.age >= 18;
},
}));
export const [PersistentStoreProvider, usePersistentStore] = createPersistentStore(
PersistentStore,
defaultStorage,
{
name: 'Test User',
age: 19,
premium: false,
hydrated: false,
},
{
hydrated: false,
},
{
logging: false,
devtool: false,
}
);
`
Wrap your app with the created Provider component.
`tsx
// app.tsx
import { PersistentStoreProvider } from './store-setup';
import Main from './main';
export default function App() {
return (
);
}
`
Consume store values using the hook.
`tsx
// main.tsx
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
import { usePersistentStore } from './store-setup';
const Main = observer(() => {
const { name, age, isAdult, hydrated, hydrate } = usePersistentStore();
useEffect(() => {
hydrate();
}, []);
if (!hydrated) {
return
Loading...
; return (
{name} is {age} years old and {isAdult ? 'is' : 'is not'} an adult.
export default Main;
`
The above example uses the default storage. You can use any storage you want by passing the storage object to the factory.
Here is an example using react-native-mmkv as the storage.
`ts
import { MMKV } from 'react-native-mmkv';
const mmkv = new MMKV();
const setItem = (key: string, value: any) => mmkv.set(key, JSON.stringify(value));
const getItem = (key: string) => {
const value = mmkv.getString(key);
if (value) {
return JSON.parse(value);
}
return null;
};
const removeItem = (key: string) => mmkv.delete(key);
const storage = {
setItem,
getItem,
removeItem,
};
export const [PersistentStoreProvider, usePersistentStore] = createPersistentStore(
PersistentStore,
storage,
{
name: 'Test User',
age: 19,
premium: false,
hydrated: false,
},
{
hydrated: false,
},
{
hydrated: false,
}
);
`
#### Type Definition
`ts
export interface StorageOptions {
setItem: (key: string, value: any) => Promise
getItem: (key: string) => Promise
removeItem: (key: string) => Promise
}
interface PersistentStoreOptions
storageKey: string;
writeDelay: number;
logging: boolean;
devtool: boolean;
onHydrate?: (store: Instance
}
const createPersistentStore:
store: T,
storage: StorageOptions,
init: SnapshotIn
disallowList?: PartialDeep
options?: Partial
) => readonly [React.FC, () => Instance
`
#### Arguments
| param | type | required | description |
| ------------ | --------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| store | T extends IAnyModelType | yes | the mst model to instantiate |StorageOptions
| storage | | yes | the storage to use. Use defaultStorage from mst-persistent-store/dist//storage to use the @react-native-async-storage/async-storage (for React Native) or localforage (for Web) backed default storage. |SnapshotIn
| init | | yes | the init data of the store |PartialDeep
| disallowList | | no | the part of the store that should not be persisted. See notes below |Partial
| options | | no | Various options to change store behavior |
#### PersistentStoreOptions
All Properties are optional.
| property | type | default | description |
| ---------- | ------------------------------ | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| storageKey | string | persistentStore | the key to use as the localforage key. Must be number
changed when using multiple stores in the same
app to avoid overriding data. |
| writeDelay | | 1500 | On Repeated Store Update, it's advisable to waitboolean
a certain time before updating the persistent
storage with new snapshot. This value controls the
debounce delay. |
| logging | | true is devboolean
false in prod | Whether to enable logging. |
| devtool | | true in dev(store: Instance
false in prod | Whether to integrate with mobx-devtool |
| onHydrate | | none | Callback to run after hydration is done. |
disallowList` is used to specify the part of the store that should not be persisted. This is useful when you have some part of the store that should not be persisted. For example, you may have a part of the store that is used for UI state management and should not be persisted.
This is a deep partial of the store snapshot. Anything passed here will replace the value on hydration.
This package is licensed under the MIT License.
Any kind of contribution is welcome. Thanks!