Want to save Mobx state in sessionStorage? 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.