Created
June 7, 2021 10:10
-
-
Save Icaruk/6799c04a27693cb00d3f28fef995ad4c to your computer and use it in GitHub Desktop.
MobX persist localStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { makeAutoObservable } from "mobx"; | |
import persist from "./persist"; | |
export default class UserStore { | |
constructor() { | |
makeAutoObservable(this); | |
persist(this, "user"); | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { autorun, set, toJS } from "mobx"; | |
/** | |
* Hace persistente un store de MobX, cargando al inicio y guardando ante cada cambio. | |
* @param {*} _this Instancia del store de MobX (cuando ya es un Obervable) | |
* @param {string} storageKey Nombre de la key del storage donde se cargará y guardará la store | |
*/ | |
export default function persist (_this, storageKey) { | |
const load = localStorage.getItem(storageKey); | |
if (load) set(_this, JSON.parse(load)); | |
autorun(() => { | |
const value = toJS(_this); | |
localStorage.setItem(storageKey, JSON.stringify(value)) | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment