mobx-state-tree-persist
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

Mobx-State-Tree Persist

Easily persist and rehydrate your MobX-State-Tree data stores.

Usage

Configure which nodes from data tree should be persisted and use the persist API. Each node can be individually configured:

Setup

const BearModel = types.model('bear')
  .props({
    number: types.optional(types.number, 0)
  });

const FishModel = types.model('fish')
  .props({
    number: types.optional(types.number, 0)
  });

const RootModel = types.model('root')
  .props({
    fish: FishModel,
    bear: BearModel,
  });

const rootStore = RootModel.create({
  fish: {},
  bear: {},
});

const persistStore = persist([
  [rootStore.bear, {key: "bear", storage: AsyncStorage}],
  [rootStore.fish, {key: "fish", storage: AsyncStorage}],
])

Rehydrated?

The call to persist returns a state tree node in intself that can obvserved in any component. The node contains a isRehydrated computed value that flips to true once each configured store has had a chance to load data.

// Example in React
import {observer} from 'mobx-react-lite';

const App = observer(() => {

  // return 'null' until store rehydrated
  if (!persistStore.isRehydrated) {
    return null;
  }

  return (
    // app content
  );
});

Options

option Description
key required - key which the data is stored within the Storage Engine.
storage required - Storage Engine the node is saved within. Any engine can be used that implements the Storage Interface
delay optional - delay timeout in ms before data should be written out to Storage Engine. Default value: 0
whitelist optional - configure which keys from the snapshot should be persisted. Default: all keys.

Storage Interface

Any Storage Engine may be used that implements the following interface:

export type Storage = {
  getItem: (key: string) => Promise<string | null | undefined>;
  setItem: (key: string, data: string) => Promise<void>;
};

Package Sidebar

Install

npm i mobx-state-tree-persist

Weekly Downloads

5

Version

0.2.0

License

MIT

Unpacked Size

24.9 kB

Total Files

8

Last publish

Collaborators

  • scottianstewart
  • keithluchtel
  • ceceppa
  • robwalkerco
  • sarahformidable
  • scott-rippey
  • michaelmerrill
  • sarmeyer
  • mariano-formidable
  • ryan.roemer
  • formidable-owner
  • formidablelabs
  • carbonrobot
  • masiddee
  • gksander