UNPKG

@bentoo/state-man

Version:

A lightweight package for state management in React applications, designed as a simplified alternative to Zustand and the Context API.

113 lines (112 loc) 2.54 kB
var d = Object.defineProperty; var f = (e, t, s) => t in e ? d(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s; var o = (e, t, s) => f(e, typeof t != "symbol" ? t + "" : t, s); import { useSyncExternalStore as h } from "react"; class i { constructor() { o(this, "observers", []); this.observers = []; } subscribe(t) { return this.observers.push(t), () => this.unsubscribe(t); } unsubscribe(t) { this.observers = this.observers.filter( (s) => s != t ); } notify() { this.observers.forEach((t) => t()); } } class m { isClientSide() { return typeof window < "u"; } } const c = new m(), S = (e, t) => { if (e.key === t.key) try { t.store.set(JSON.parse(e.newValue || "")); } catch (s) { console.log(s); } }; function g(e) { c.isClientSide() && window.addEventListener("storage", (t) => S(t, e)); } class l { constructor(t, s) { this.initialData = t, this.observable = s; } set(t) { typeof t == "function" ? this.initialData = t(this.initialData) : this.initialData = t, this.observable.notify(); } get() { return this.initialData; } } const v = (e, t, s) => h(e, t, s); function I(e) { let t, s; const n = (e == null ? void 0 : e.setItem) !== void 0; if (n) { let r = e; t = r.observable, s = r.store; const { key: a } = e; g({ key: a, store: s }); } else t = new i(), s = new l(e, t); return () => { const r = () => n ? e == null ? void 0 : e.initialData : e; return { state: v( t.subscribe.bind(t), s.get.bind(s), r ), setState: n ? e.setItem.bind(s) : s.set.bind(s) }; }; } function D(e) { if (!e.name) throw new Error("You must provide a name for the persisted store"); let t, s; c.isClientSide() ? s = e.storage || window.localStorage : s = e.storage || { getItem: () => null, setItem: () => null, length: 0, clear: () => { }, key: () => null, removeItem: () => { } }; const n = s.getItem(e.name); if (n) try { t = JSON.parse(n); } catch { t = e.data, s.setItem(e.name, JSON.stringify(e.data)); } else t = e.data, s.setItem(e.name, JSON.stringify(e.data)); const r = new i(), a = new l(t, r), u = (b) => { a.set(b), s.setItem(e.name, JSON.stringify(a.get())); }; return { key: e.name, store: a, observable: r, setItem: u, initialData: e.data }; } export { I as create, D as persist };