UNPKG

@preact-hooks/unistore

Version:

A custom Preact hook to wire up components to Unistore.

2 lines (1 loc) 1.11 kB
import{useContext as r,useReducer as e,useRef as t,useMemo as n,useLayoutEffect as c,useEffect as u}from"preact/hooks";import{createContext as o}from"preact";var a="undefined"!=typeof window?c:u,i=(r,e)=>r===e,l=r=>(r=r.split(/\s*,\s*/),e=>{for(var t={},n=0;n<r.length;n++)t[r[n]]=e[r[n]];return t}),s=o(null),v=s.Provider,f=()=>r(s),h=function(r,n){void 0===n&&(n=i);var c,u=f(),[,o]=e(r=>r+1,0),s=t(null),v=t(null),h=t(null),p="string"==typeof r;try{if(s.current!==r||h.current){var d=u.getState();c=p?l(r)(d):r(d)}else c=v.current}catch(r){var g="An error occured while selecting the store state: "+r.message+".";throw h.current&&(g+="\nThe error may be related to the previous error:\n"+h.current.stack+"\n\nOriginal stack trace:"),new Error(g)}return a(()=>{s.current=p?l(r):r,v.current=c,h.current=null}),a(()=>{var r=()=>{try{var r=s.current(u.getState());if(n(r,v.current))return;v.current=r}catch(r){h.current=r}o({})},e=u.subscribe(r);return r(),()=>e()},[u]),c},p=r=>{var e=f();return n(()=>e.action(r),[e,r])};export{s as StoreContext,v as StoreProvider,p as useAction,h as useSelector,f as useStore};