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.39 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 u=[];return{get value(){return n},set value(e){n=e,u.forEach((e=>e(n))),r&&s&&l&&localStorage.setItem(r,JSON.stringify(o(l,s)))},subscribe:e=>{u.push(e)}}},o=(e,t)=>t.reduce(((t,r)=>{var o;return t[r]=null==(o=e[r])?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 u=null==(o=t[s])?void 0:o.value;if(void 0===u)throw new Error(`State ${e} not found in store.`);if(void 0!==r)if(0===n.length)u!==r(u)&&(t[s].value=r(u));else{const e=((e,t,r)=>{const o={...t};let l=o;return e.forEach(((t,o)=>{o===e.length-1?l[t]=r(l[t]):(l[t]={...l[t]||{}},l=l[t])})),o})(n,u,r);t[s].value=e}return 0===n.length?u:((e,t)=>{let r=t;for(const t of e){if(!r||"object"!=typeof r)return;r=r[t]}return r})(n,u)},n=(r,o)=>{var l;const n=r.split(".")[0],[,u]=e(((e,t)=>t),null==(l=o[n])?void 0:l.value);return t((()=>{o[n].subscribe((e=>{u(e)}))}),[n,o]),s(r,o)};export{l as createStore,s as stateValue,n as useStateListener};