How to save Mobx state in sessionStorage

后端 未结 4 659
无人共我
无人共我 2021-02-13 21:54

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.

4条回答
  •  渐次进展
    2021-02-13 22:12

    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);
      }
    }
    

提交回复
热议问题