Skip to content

Instantly share code, notes, and snippets.

@Icaruk
Created June 7, 2021 10:10
Show Gist options
  • Save Icaruk/6799c04a27693cb00d3f28fef995ad4c to your computer and use it in GitHub Desktop.
Save Icaruk/6799c04a27693cb00d3f28fef995ad4c to your computer and use it in GitHub Desktop.
MobX persist localStorage
import { makeAutoObservable } from "mobx";
import persist from "./persist";
export default class UserStore {
constructor() {
makeAutoObservable(this);
persist(this, "user");
};
};
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