foxact
Version:
React Hooks/Utils done right. For browser, SSR, and React Server Components.
1 lines • 2.1 kB
JavaScript
;require("client-only");var e=require("react"),o=require("../noop/index.cjs"),t=require("../use-isomorphic-layout-effect/index.cjs"),n=require("../no-ssr/index.cjs");const r=e=>"function"==typeof e,a=e=>e;function i(){throw n.noSSRError("useLocalStorage cannot be used on the server without a serverValue")}exports.createStorage=function(n){const l="localStorage"===n?"foxact-use-local-storage":"foxact-use-session-storage",c="localStorage"===n?"foxact/use-local-storage":"foxact/use-session-storage",s="undefined"==typeof window?o.noop:e=>{window.dispatchEvent(new CustomEvent(l,{detail:e}))},u="undefined"==typeof window?o.noop:(e,o)=>{try{window[n].setItem(e,o)}catch(e){console.warn("[".concat(c,"] Failed to set value to ").concat(n,", it might be blocked"))}finally{s(e)}},d="undefined"==typeof window?o.noop:e=>{try{window[n].removeItem(e)}catch(e){console.warn("[".concat(c,"] Failed to remove value from ").concat(n,", it might be blocked"))}finally{s(e)}},w=e=>{if("undefined"==typeof window)return null;try{return window[n].getItem(e)}catch(e){return console.warn("[".concat(c,"] Failed to get value from ").concat(n,", it might be blocked")),null}};return{useStorage:function(n,c){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{raw:!1,serializer:JSON.stringify,deserializer:JSON.parse};const f=e.useCallback(e=>{if("undefined"==typeof window)return o.noop;const t=o=>{"key"in o&&o.key!==n||e()},r=o=>{o.detail===n&&e()};return window.addEventListener("storage",t),window.addEventListener(l,r),()=>{window.removeEventListener("storage",t),window.removeEventListener(l,r)}},[n]),v=s.raw?a:s.serializer,y=s.raw?a:s.deserializer,g=void 0===c?i:()=>v(c),m=e.useSyncExternalStore(f,()=>w(n),g),p=e.useMemo(()=>null===m?null:y(m),[m,y]),h=e.useCallback(e=>{try{const o=r(e)?e(null!=p?p:null):e;null===o?d(n):u(n,v(o))}catch(e){console.warn(e)}},[n,v,p]);return t.useLayoutEffect(()=>{null===w(n)&&void 0!==c&&u(n,v(c))},[y,n,v,c]),[null===p?void 0===c?null:c:p,h]},useSetStorage:(o,t)=>e.useCallback(e=>{try{null===e?d(o):u(o,t(e))}catch(e){console.warn(e)}},[o,t])}};