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