UNPKG

origami-state-manager

Version:

A global state management library that is light and requires minimal boilerplate. OSM stands out for its ability to seamlessly access and update global states from both React and non-React environments.

2 lines (1 loc) 1.47 kB
import{useReducer as e,useEffect as t}from"react";const r=(e,t)=>{const r=null==t?void 0:t.storeName,l=null==t?void 0:t.storeSubscribe,s=null==t?void 0:t.storeKeys;let n=e;const a=[];return{get value(){return n},set value(e){n=e,a.forEach((e=>e(n))),r&&s&&l&&localStorage.setItem(r,JSON.stringify(o(l,s)))},subscribe:e=>{a.push(e)}}},o=(e,t)=>t.reduce(((t,r)=>{var o;return t[r]=null===(o=e[r])||void 0===o?void 0:o.value,t}),{}),l=(e,t="")=>{const o=t&&localStorage.getItem(t)?JSON.parse(localStorage.getItem(t)||"{}"):e;t&&!localStorage.getItem(t)&&localStorage.setItem(t,JSON.stringify(o));const l=Object.keys(o),s={};return l.forEach((e=>{s[e]=r(o[e],{storeName:t,storeKeys:l,storeSubscribe:s})})),s},s=(e,t,r)=>{var o;const l=e.split("."),s=l[0],n=l.slice(1);let a=null===(o=t[s])||void 0===o?void 0:o.value;if(void 0===a)throw new Error(`State ${e} not found in store.`);if(void 0!==r)if(0===n.length)a!==r(a)&&(t[s].value=r(a));else{const e=((e,t,r)=>{let o=t;const l=Object.assign({},o);let s=l;return e.forEach(((t,o)=>{o===e.length-1?s[t]=r(s[t]):(s[t]=Object.assign({},s[t]||{}),s=s[t])})),l})(n,a,r);t[s].value=e}return 0===n.length?a:((e,t)=>{let r=t;for(const t of e){if(!r||"object"!=typeof r)return;r=r[t]}return r})(n,a)},n=(r,o)=>{var l;const n=r.split(".")[0],[,a]=e(((e,t)=>t),null===(l=o[n])||void 0===l?void 0:l.value);return t((()=>{o[n].subscribe((e=>{a(e)}))}),[n,o]),s(r,o)};export{l as createStore,s as stateValue,n as useStateListener};