Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Mobx state in sessionStorage

Trying to essentially accomplish this https://github.com/elgerlambert/redux-localstorage which is for Redux but do it for Mobx. And preferably would like to use sessionStorage. Is there an easy way to accomplish this with minimal boilerplate?

like image 776
anthony-dandrea Avatar asked Oct 27 '16 19:10

anthony-dandrea


People also ask

How do you persist MobX state?

To persist this observable we simply add a persist to it: When you update the observable variable, which is marked with persist , mobx-persist will automatically save the change using AsyncStorage. That's it!

Should I use MobX state tree?

Ten reasons you should use MobX-State-Tree:Via runtime type checking, you can't accidentally assign the wrong data type to a property. TypeScript can infer static types from your runtime types automatically. Every update to your data is traced and you can quickly generate snapshots of your state at any time.

How does MobX state tree work?

The tree consists of mutable, but strictly protected objects enriched with runtime type information. In other words, each tree has a shape (type information) and state (data). From this living tree, immutable, structurally shared, snapshots are automatically generated.

Is MobX fast?

MobX is very fast, often even faster than Redux, but here are some tips to get most out of React and MobX. Most apply to React in general and are not specific to MobX. Note that while it's good to be aware of these patterns, usually your application will be fast enough even if you don't worry about them at all.


1 Answers

The easiest way to approach this would be to have a mobx "autorun" triggered whenever any observable property changes. To do that, you could follow my answer to this question.

I'll put some sample code here that should help you get started:

function autoSave(store, save) {
  let firstRun = true;
  mobx.autorun(() => {
    // This code will run every time any observable property
    // on the store is updated.
    const json = JSON.stringify(mobx.toJS(store));
    if (!firstRun) {
      save(json);
    }
    firstRun = false;
  });
}

class MyStore {
  @mobx.observable prop1 = 999;
  @mobx.observable prop2 = [100, 200];

  constructor() {
    this.load();
    autoSave(this, this.save.bind(this));
  }

  load() {
    if (/* there is data in sessionStorage */) {
      const data = /* somehow get the data from sessionStorage or anywhere else */;
      mobx.extendObservable(this, data);
    }
  }

  save(json) {
    // Now you can do whatever you want with `json`.
    // e.g. save it to session storage.
    alert(json);
  }
}
like image 123
Mouad Debbar Avatar answered Nov 15 '22 23:11

Mouad Debbar